0
我有RSA加密和Base 64編碼文本解密的問題。當我直接解密加密文本(無符號字符*),那麼一切都很好,我得到正確的結果。但是,當我做base64編碼,比openssl無法解密數據,儘管base64解碼數據與加密數據完全相同:RSA解密與openSSL
例如(首先是加密結果和第二個base 64解碼結果。相當好)
加密 - 。SSA£®Òz>Ô
已解碼的字符串 - ߨ¨zz>Ô
代碼:?
+(NSString *) rsaEncryptedStringFromText: (NSString *) text
{
const char *message = [text UTF8String];
NSLog(@"message - %s", message);
int bufSize;
NSString *keyFilePath = [[NSBundle mainBundle] pathForResource:@"publicKey" ofType:@"pem"];
FILE *keyfile = fopen([keyFilePath UTF8String], "r");
RSA *rsa = PEM_read_RSA_PUBKEY(keyfile, NULL, NULL, NULL);
if (rsa == NULL)
{
return nil;
}
int key_size = RSA_size(rsa);
unsigned char *encrypted = (unsigned char *) malloc(key_size);
bufSize = RSA_public_encrypt(strlen(message), (unsigned char *) message, encrypted, rsa, RSA_PKCS1_PADDING);
if (bufSize == -1)
{
RSA_free(rsa);
return nil;
}
NSLog(@"encrypted - %s", encrypted);
NSData *encryptedData = [NSData dataWithBytes:encrypted length:strlen((const char *)encrypted)];
NSString *base64 = [encryptedData base64Encoding];
RSA_free(rsa);
return base64;
}
+(NSString *) rsaDecryptToStringFromText: (NSString *) text
{
//NSLog(@"text - %@", text);
NSData *decodedData = [NSData dataWithBase64EncodedString: text];
unsigned char* message = (unsigned char*) [decodedData bytes];
NSLog(@"decoded string - %s", message);
RSA *privKey = NULL;
FILE *priv_key_file;
unsigned char *ptext;
NSString *keyFilePath = [[NSBundle mainBundle] pathForResource:@"privateKeyPair" ofType:@"pem"];
priv_key_file = fopen([keyFilePath UTF8String], "rb");
ERR_print_errors_fp(priv_key_file);
privKey = PEM_read_RSAPrivateKey(priv_key_file, NULL, NULL, NULL);
int key_size = RSA_size(privKey);
ptext = malloc(key_size);
int outlen = RSA_private_decrypt(key_size, (const unsigned char*)message, ptext, privKey, RSA_PKCS1_PADDING);
if(outlen < 0) return nil;
RSA_free(privKey);
return [NSString stringWithUTF8String: (const char *)ptext];
}
Base 64 encoding-d ecoding與此完成:
http://www.iphonedevsdk.com/forum/iphone-sdk-development/21689-base-64-string-help.html#post98080
這些字符串不一樣(¶後有一個換行符)。 – trojanfoe
哪裏?看不到... –
我認爲你的代碼非常糟糕。你爲什麼要爲加密數據分配'key_size'? 'strlen(加密)'返回正確的長度(我懷疑)。你永遠不會關閉'FILE *'並且永遠不會釋放你分配的內存。我並不感到驚訝,它不起作用。 – trojanfoe