2011-11-30 43 views
0

我發現了一個關於OPENSSL DES的例子,當我將這個例子應用到Objective-C程序中時,解密後的文本與我輸入的內容不相等。IPHONE使用OPENSSL進行DES加密的Objective-C程序

textField.text是輸入文本框

任何人都可以幫我嗎?非常感謝!!!

爲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);  
}  
------------------------------------------------  
+0

DES永遠不會在21世紀被使用。 –

回答

0

此行

encrypted=(char*)malloc(sizeof(clear)); 

不會做你的想法。在32位系統上,sizeof(clear)將是4,因爲它是指針的大小,而不是指向的數據的長度。所以你可能只是加密/解密4個字節,而你正在打印出這4個字節加上一些垃圾。

+0

感謝JeremyP,這個函數可以替代「sizeof」,因爲我是C語言的新手。 – keithlsp

+0

如果你想加密整個字符串,包括它的終止空字符,你需要'strlen(clear)+ 1'。請注意,結果是一個字節數組,**不是C空值終止的字符串**。 – JeremyP

+0

謝謝JermyP,我的問題已經解決了!非常感謝!!!! – keithlsp