我遇到RSA加密和Base 64编码文本解密的问题。当我解密直接加密的文本(unsigned char *)时,一切都很好,我得到了正确的结果。但是当我做base64编码时,openssl无法解密数据,尽管base64解码数据与加密数据完全相同:
例如(首先是加密结果和第二个基本64解码结果。解码第一个char *直接工作得很好。)
加密 - ßÁ¨£ÒÒ>Ô 解码后的字符串 - ßÁ¨£ÒÒ>Ô 代码: } } Base 64编码解码用这个完成: http://www.iphonedevsdk.com/forum/iphone-sdk-development/21689-base-64-string-help.html#post98080 +(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];