0

我对 RSA 加密和 Base 64 编码文本解密有疑问。当我直接解密加密文本(unsigned char *)时,一切正常,我得到正确的结果。但是当我进行 base64 编码时,openssl 无法解密数据,尽管 base64 解码的数据与加密数据完全相同:

例如(第一个是加密结果和第二个base 64解码结果。直接解码第一个char *效果很好。)

加密 - ßÁ¨£®Òz>Ô‹n.€Ö∫BÔ–∂ü∏ÕD⁄UÖáµ)ûKufi wÆ&_è”eëõ~gK∂¶$kŸƒ∫ª`ÔfΩ˙˛{∆_MªÔëbP Q¶FL±Ü;! ü•◊s>ħΔ◊⁄≤ò˙ˇCWôVÂzôzíö≤ÙU¶?⁄l[*H?o\ñ>ƒ<'4mœ“Lr Íhh

解码字符串 - ßÁ¨£®Òz>Ô‹n.€Ö∫BÔ–∂ü∏ÕD⁄UÖáµ)ûKufi wÆ&_è”eëõ~gK∂¶$kŸƒ∫ª`ÔfΩ˙˛{∆_MªÔëbP Q¶FL±Ü; !ü•◊s>ħΔ◊⁄≤ò˙ˇCWôVÂzôzíö≤ÙU¶?⁄l[*H?o\ñ>ƒ<'4mœ“Lr Íhh

代码:

+(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 编码-解码是这样完成的:

http://www.iphonedevsdk.com/forum/iphone-sdk-development/21689-base-64-string-help.html#post98080

4

1 回答 1

-1

主要问题出在 base64 编码+解码类中。切换到QSutilities,一切正常。

于 2012-05-11T10:55:38.553 回答