IPHONE Objective-C program using OPENSSL perform DES Encryption - iphone

I have found an example about OPENSSL DES, when I applied this example into Objective-C program, the decrypted text was not equal to what I have input.
textField.text is the input textbox
Can anyone help me? Many thanks!!!
for e.g,
when I input "test", the decrypted text ="test&\264"
when I input "Enter an Text here", the decrypted text ="Ente"
when I input "1234567890", the decrypted text ="1234h&\311"
//ENCRYPTION
char* desen(char *clear, int size)
{
printf("Encrypted text\t %s \n",clear);
char *encrypted;
char key[]="password";
encrypted=(char*)malloc(sizeof(clear));
static char* Res;
int n=0;
DES_cblock Key2;
DES_key_schedule schedule;
Res = ( char * ) malloc( sizeof(clear) );
// Prepare the key for use with DES_cfb64_encrypt /
memcpy( Key2, key,8);
DES_set_odd_parity( &Key2 );
DES_set_key_checked( &Key2, &schedule );
// Encryption occurs here /
DES_cfb64_encrypt( ( unsigned char * ) clear, ( unsigned char * ) Res,
sizeof(clear), &schedule, &Key2, &n, DES_ENCRYPT );
memcpy(encrypted,Res, sizeof(clear));
printf("Key:%s\n",encrypted);
return encrypted;
}
//------------------------------------------------
//DECRYPTION-------------------------------
char* desde(char *clear, int size)
{
char *decrypted;
char key[]="password";
decrypted=(char*)malloc(sizeof(clear));
static char* Res;
int n=0;
DES_cblock Key2;
DES_key_schedule schedule;
Res = ( char * ) malloc( sizeof(clear) );
// Prepare the key for use with DES_cfb64_encrypt /
memcpy( Key2, key,8);
DES_set_odd_parity( &Key2 );
DES_set_key_checked( &Key2, &schedule );
// Encryption occurs here /
DES_cfb64_encrypt( ( unsigned char * ) clear, ( unsigned char * ) Res,
sizeof(clear), &schedule, &Key2, &n, DES_DECRYPT );
memcpy(decrypted,Res, sizeof(clear));
printf("Key:%s\n",decrypted);
return decrypted;
}
//------------------------------------------------
//----------Button------------------------------
- (IBAction)calculateDES_ENCRYPT:(id)sender
{
char key[]="password";
char *en;
char *de;
NSString *string = textField.text;
const char *temp=[string fileSystemRepresentation];
int len=strlen(temp);
char clear[len+1];
//char clear[50];
strcpy(clear,temp);
en=desen( clear,len+1);
de= desde(en, len+1);
}
------------------------------------------------

This line
encrypted=(char*)malloc(sizeof(clear));
doesn't do what you think. On a 32 bit system, sizeof(clear) will be 4 because it is the size of the pointer, not the length of the data pointed to. So you are probably only encrypting/decrypting 4 bytes and you are printing out those 4 bytes plus some garbage.

Related

Pass String array as input into external C function

I would like to pass a String vector into an external C function.
In a minimal example I just want to pass the String vectors (or 1D array) through the C function.
My Modelica function looks like:
function testreadstri
input String instri[2];
output String outstri[2];
external "C" test_stri(instri,, size(instri, 1), outstri);
annotation (Include="#include <ebcmysql.cpp>", Library="libmysql");
end testreadstri;
My C fucntion looks like:
void test_stri(const char* thestring, size_t nLines, const char **testresult)
{
//bout = 12.3;
size_t iLines;
//size_t nLines;
iLines = 0;
//nLines = 1;
while ( iLines <= nLines ) {
<LINE_OF_INTEREST>
iLines++;
}
}
I tried for <LINE_OF_INTEREST> the following lines:
testresult[iLines] = thestring[iLines];
strcpy(testresult[iLines], thestring[iLines]);
What works, but of course does not pass the input through as an output, is:
testresult[iLines] = "aTestString";
Is there any possibility to handle Modelica input String vectors in the external C function?
Thanks in advance!
Here's a short, self-contained and compilable example demonstrating both input string and output string handling of a pure external function in Modelica
model Model
function testreadstri
input String instri[2];
output String outstri[2];
external "C" test_stri(instri, size(instri, 1), outstri, size(outstri, 1));
annotation(Include="
#include \"ModelicaUtilities.h\"
#include <stdlib.h>
#include <string.h>
void test_stri(const char** thestring, size_t nLinesIn, const char** testresult, size_t nLinesOut)
{
size_t iLines;
// example for input string handling
for (iLines = 0; iLines < nLinesIn; iLines++) {
ModelicaFormatMessage(\"%s\\n\", thestring[iLines]);
}
// example for output string handling
for (iLines = 0; iLines < nLinesOut; iLines++) {
char* line = ModelicaAllocateStringWithErrorReturn(6);
if (line != NULL) {
strcpy(line, \"result\");
testresult[iLines] = line;
}
}
}");
end testreadstri;
String s[:] = testreadstri({"first", "second"});
end Model;
Yes, this is supported by the Modelica specification, see https://specification.modelica.org/v3.4/Ch12.html#argument-type-mapping.

UEFI LoadImage hangs

I am looking at using Bootservices function LoadImage to load a UEFI application image from memory. Function parameters are:
typedef
EFI_STATUS
LoadImage (
IN BOOLEAN BootPolicy,
IN EFI_HANDLE ParentImageHandle,
IN EFI_DEVICE_PATH_PROTOCOL *DevicePath,
IN VOID *SourceBuffer OPTIONAL,
IN UINTN SourceSize,
OUT EFI_HANDLE *ImageHandle
);
I have sourcebuffer in memory and populated with the PE/COFF image to load.
I pass that in under SourceBuffer and set DevicePath to the following:
MEMMAP_DEVICE_PATH mempath[2];
mempath[0].Header.Type = HARDWARE_DEVICE_PATH;
mempath[0].Header.SubType = HW_MEMMAP_DP;
mempath[0].Header.Length[0] = (UINT8)sizeof(mempath);
mempath[0].Header.Length[1] = (UINT8)(sizeof(mempath)>> 8);
mempath[0].MemoryType = EfiLoaderCode;
mempath[0].StartingAddress = (UINT32)buff_ptr;
mempath[0].EndingAddress = (UINT32)(buff_ptr + BUFF_SIZE);
mempath[1].Header.Type = END_DEVICE_PATH_TYPE;
mempath[1].Header.SubType = END_ENTIRE_DEVICE_PATH_SUBTYPE;
mempath[1].Header.Length[0] = (UINT8)sizeof(EFI_DEVICE_PATH);
mempath[1].Header.Length[1] = (UINT8)(sizeof(EFI_DEVICE_PATH)>> 8);
When I call load image the application hangs. I have set up visual studio to allow me to debug UEFI EDK2 source and have isolated where i'm stuck. Below is the EDK2 call that I appear to be stuck in. DevicePath is set to the mempath I setup above. Am I configuring my path incorrectly such that I never exit the below?
EFI_STATUS
EFIAPI
CoreLocateDevicePath (
IN EFI_GUID *Protocol,
IN OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath,
OUT EFI_HANDLE *Device
)
{
......
EFI_DEVICE_PATH_PROTOCOL *SourcePath;
SourcePath = *DevicePath;
TmpDevicePath = SourcePath;
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//I NEVER GET OUT OF THIS LOOP!!!
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
while (!IsDevicePathEnd (TmpDevicePath)) {
if (IsDevicePathEndInstance (TmpDevicePath)) {
break;
}
TmpDevicePath = NextDevicePathNode (TmpDevicePath);
}
For more context this is the UDK callstack of where i'm stuck
DxeCore.dll!CoreLocateDevicePath(GUID * Protocol, EFI_DEVICE_PATH_PROTOCOL * * DevicePath, void * * Device) Line 452 C
DxeCore.dll!CoreLoadImageCommon(unsigned char BootPolicy, void * ParentImageHandle, EFI_DEVICE_PATH_PROTOCOL * FilePath, void * SourceBuffer, unsigned int SourceSize, unsigned __int64 DstBuffer, unsigned int * NumberOfPages, void * * ImageHandle, unsigned __int64 * EntryPoint, unsigned int Attribute) Line 1089 C
DxeCore.dll!CoreLoadImage(unsigned char BootPolicy, void * ParentImageHandle, EFI_DEVICE_PATH_PROTOCOL * FilePath, void * SourceBuffer, unsigned int SourceSize, void * * ImageHandle) Line 1425 C
MyApplication.dll!efi_main(void * ImageHandle, EFI_SYSTEM_TABLE * SystemTable) Line 2588 C
Found my answer, sharing here for others:
I based my original mempath off of the grub source:http://git.savannah.gnu.org/cgit/grub.git/tree/grub-core/loader/arm64/linux.c?id=7a210304ebfd6d704b4fc08fe496a0c417441879#n249
I changed the type of end point to instance, the size field of the header. I properly exit the loop now. My original header had the size of the entire structure, so I believe when trying to iterate to the next endpoint it was winding up with an invalid one, instead of going to my correct second element. Here is what I used:
mempath[0].Header.Type = HARDWARE_DEVICE_PATH;
mempath[0].Header.SubType = HW_MEMMAP_DP;
mempath[0].Header.Length[0] = (UINT8)sizeof(MEMMAP_DEVICE_PATH);
mempath[0].Header.Length[1] = (UINT8)(sizeof(MEMMAP_DEVICE_PATH)>> 8);
mempath[0].MemoryType = EfiLoaderCode;
mempath[0].StartingAddress = (UINT32)buff_ptr;
mempath[0].EndingAddress = (UINT32)(buff_ptr + SIZEOF_HELLO_EFI);
mempath[1].Header.Type = END_DEVICE_PATH_TYPE;
mempath[1].Header.SubType = END_INSTANCE_DEVICE_PATH_SUBTYPE;
mempath[1].Header.Length[0] = (UINT8)sizeof(EFI_DEVICE_PATH);
mempath[1].Header.Length[1] = (UINT8)(sizeof(EFI_DEVICE_PATH)>> 8);

how to add FileAttachment annotations of pdf

Hello i am using this library for implementation of annotation but facing one issue of attachment of image it provide PdfFileSpec objective c++ function i tried to convert this function to objective c but getting error in below image
class PODOFO_DOC_API PdfFileSpec : public PdfElement {
public:
PdfFileSpec( const char* pszFilename, bool bEmbedd, PdfDocument* pParent );
PdfFileSpec( const char* pszFilename, bool bEmbedd, PdfVecObjects* pParent );
/* Petr P. Petrov 17 September 2009*/
/** Embeds the file in memory from "data" buffer under "pszFileName" fie name.
*/
PdfFileSpec( const char* pszFilename, const unsigned char* data, ptrdiff_t size, PdfVecObjects* pParent);
PdfFileSpec( PdfObject* pObject );
/** \returns the filename of this file specification.
* if no general name is available
* it will try the Unix, Mac and DOS keys too.
*/
const PdfString & GetFilename() const;
+(void)createFreeTextAnnotationOnPage:(NSInteger)pageIndex doc:(PdfMemDocument*)aDoc rect:(CGRect)aRect borderWidth:(double)bWidth title:(NSString*)title content:(NSString*)content bOpen:(Boolean)bOpen color:(UIColor*)color {
PoDoFo::PdfMemDocument *doc = (PoDoFo::PdfMemDocument *) aDoc;
PoDoFo::PdfPage* pPage = doc->GetPage(pageIndex);
if (! pPage) {
// couldn't get that page
return;
}
PoDoFo::PdfAnnotation* anno;
PoDoFo::EPdfAnnotation type= PoDoFo::ePdfAnnotation_Text;
PoDoFo::PdfRect rect;
rect.SetBottom(aRect.origin.y);
rect.SetLeft(aRect.origin.x);
rect.SetHeight(aRect.size.height);
rect.SetWidth(aRect.size.width);
NSData *data=UIImagePNGRepresentation([UIImage imageNamed:#"Add_button.png"]);
anno = pPage->CreateAnnotation(type , rect);
NSString *myString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
PoDoFo::PdfString sTitle([title UTF8String]);
PoDoFo::PdfString sContent([content UTF8String]);
PoDoFo::PdfFileSpec data1([myString UTF8String], true, doc);
}
I don't see why you are using reinterpret_cast, and it's certainly being misused in the construction of data1.
Have you simply tried:
PoDoFo::PdfString sTitle([title UTF8String]);
PoDoFo::PdfString sContent([content UTF8String]);
PoDoFo::PdfFileSpec data1([myString UTF8String], true, doc);

QString encoding with special character

I m trying to convert QString with special character to const char but I did not succeed.
my function is:
void class::func(const QString& fileName) // fileName = "â.tmp"
{
qDebug()<< fileName; // display "â.tmp"
const char* cfileName = fileName.toAscii().data();
qDebug() << cfileName; // display "a?.tmp"
}
qDebug()<< fileName display the true value that is "â.tmp" but after converting it to const a char*, I do not succeed to have the right value.
In the second time I try to use
const char* cfileName = QString::fromUtf8(fileName.toAscii().data());
but I did not still have the right value, it display the same thing: a?.tmp.
How can I fix this?
ASCII character set does not have the character â, so what you are trying to do is impossible.
You could try this:
const char* cfileName = = fileName.toUtf8().data();

ADXL345 atmega16

i just started the project which requiers to connect ADXL345 to my Atmega16. I want to put device id on screen and read axis. So far i cant communicate with ADXL345. ON LCD only appears 0 I would be gratefull for any help.
#include <avr/io.h>
#include <stdlib.h>
#include <util/delay.h>
#include "hd44780.h"
#define F_CPU 1000000UL
/*-----------------------Rejestry ADXL345---------------------*/
char POWER_CTL = 0x2D; //Power Control Register 0x08 measurement
char DATA_FORMAT = 0x31;
char BW_RATE = 0X2C;
char FIFO = 0x38; //fifo ctl
char DATAX0 = 0x32; //X-Axis Data 0
char DATAX1 = 0x33; //X-Axis Data 1
char DATAY0 = 0x34; //Y-Axis Data 0
char DATAY1 = 0x35; //Y-Axis Data 1
char DATAZ0 = 0x36; //Z-Axis Data 0
char DATAZ1 = 0x37; //Z-Axis Data 1
char DEVICEID = 0x00;
#define Read_Byte_SPI( addr ) ADXL_write( 0x80 | addr , 0xFF );
/*------------------PORTY SPI---------------*/
#define SPI_CS PB4
#define DDR_SPI DDRB
#define DD_MOSI PB5
#define DD_MIOS PB6
#define DD_SCK PB7
/*vcc<->vs*/
//--------------------------------------Funkcje-------------------
unsigned int init_port(void) //ports 4 lcd
{DDRD =0x00; PORTD =0x07 ; }
/*function 4 lcd*/
static void lcd( int a){ LCD_LOCATE(2,0); char buff[2]; char tab[2]; /*itoa(a,buff,10);*/ sprintf(a, %d", buff); lcd_puts(buff);
}
/**
* This writes to a register with the data passed to the address passed
* #param unsigned char cReg - the address of the register you wish to write to
* #param unsigned char cData - the data you wish to write to the register
*/
unsigned char ADXL_write(unsigned char cReg, unsigned char cData){
set_spics();
/* Start transmission send register */
SPDR = cReg;
/* Wait for transmission complete */
while(!(SPSR & (1<<SPIF)))
{ /* NOOP */ }
SPDR = cData;
/* Wait for transmission complete */
while(!(SPSR & (1<<SPIF)))
{ /* NOOP */ }
clear_spics();
return SPDR;
}
uint8_t ADXL_read(unsigned char addr) { // read ADXL345 - 128+ addrs, back 8 bits - found this in another topic
int8_t ans;
set_spics();
SPDR = 0x08 | addr;
loop_until_bit_is_set(SPSR, SPIF);
SPDR = 0xFF;
loop_until_bit_is_set(SPSR, SPIF);
ans = SPDR;
clear_spics();
return(ans);}
//inicjalizacjia SPI
void Init_SPI(){
// make the MOSI, SCK, and SS pins outputs
DDRB |= ( 1 << DD_MOSI ) | ( 1 << DD_SCK ) | ( 1 << SPI_CS );
DDRB &= ~( 1 << DD_MIOS );
/* Enable SPI, Master, set clock rate fck/128 */
SPCR = (1<<SPE)|(1<<MSTR)|(1<<SPR0)|(1<<SPR1);
}
//Control SS=CHIP SELECT ADXL345
void clear_spics(){
PORTB |= _BV(SPI_CS); // high
_delay_ms(30);}
void set_spics(){
PORTB &=~ _BV(SPI_CS); // low
_delay_ms(30);}
void ADXL_init(void){
//init ADXL
ADXL_write(DATA_FORMAT,0x08); //pełna rozdzielczość DATASHEET STRONA 26 4SPI
ADXL_write(BW_RATE, 0x0A) ; //100hz
ADXL_write(POWER_CTL,0x08);
ADXL_write(FIFO, 0); //FIFO Wylacozny
}
/*------------------------główna petla---------------------------*/
int main(void)
{
/* tab for strings */
char str1[] = "Czujnik ADXL 345";
/* init lcd*/
lcd_init();
/* LCD UP */
LCD_DISPLAY(LCDDISPLAY);
LCD_CLEAR;
LCD_LOCATE(1,1);
lcd_puts(str1);
init_port();/*port init*/
Init_SPI();//SPIUP
_delay_ms(50);
ADXL_init(); //ADXL345 config
_delay_ms(50);
while(1)
{
int8_t k;
k=Read_Byte_SPI( DEVICEID );
lcd(k);
_delay_ms(5000);
k=ADXL_read(DATAX0);
lcd(k);
_delay_ms(5000);
}
`>