首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用公钥加密

使用公钥加密
EN

Stack Overflow用户
提问于 2013-05-31 05:48:26
回答 1查看 745关注 0票数 0

我的代码:

代码语言:javascript
复制
SecKeyRef oPublicKey = [self getPublicKeyRef];
SecKeyRef oPrivateKey = [self getPrivateKeyRef];

CFDictionaryRef myDictionary;

CFTypeRef keys[2];
CFTypeRef values[2];

// Initialize dictionary of key params
keys[0] = kSecAttrKeyType;
values[0] = kSecAttrKeyTypeRSA;
keys[1] = kSecAttrKeySizeInBits;
int iByteSize = 1024;
values[1] = CFNumberCreate( NULL, kCFNumberIntType, &iByteSize );
myDictionary = CFDictionaryCreate( NULL, keys, values, sizeof(keys) / sizeof(keys[0]), NULL, NULL );

// Generate keys
OSStatus status = SecKeyGeneratePair( myDictionary, &oPublicKey, &oPrivateKey );
if ( status != 0 )
    NSLog( @"SecKeyGeneratePair failed" );

// Encrypt some data
uint8_t* pPlainText = (uint8_t*)"6921";

uint8_t aCipherText[1024];
size_t iCipherLength = 1024;
status = SecKeyEncrypt( oPublicKey, kSecPaddingPKCS1, pPlainText, strlen( (char*)pPlainText ) + 1, &aCipherText[0], &iCipherLength );

if ( status != 0 )
    NSLog( @"SecKeyEncrypt failed" );

NSMutableData *data12=[[NSMutableData alloc] init];
[data12 appendBytes:aCipherText length:strlen( (char*)aCipherText ) + 1];
NSString *string1 = [[NSString alloc]initWithData:data12 encoding:NSASCIIStringEncoding];
NSLog(@"Encrypted Text:::%@",string1);

// Decrypt the data
uint8_t aPlainText[1024];
size_t iPlainLength = 1024;
status = SecKeyDecrypt( oPrivateKey, kSecPaddingPKCS1, &aCipherText[0], iCipherLength, &aPlainText[0], &iPlainLength );
if ( status != 0 )
    NSLog( @"SecKeyDecrypt failed" );

NSLog(@"FINAL decrypted text: %s", aPlainText);

我使用这段代码进行加密,但是我们得到的输出如下:

(( N$) )¥=wÞ¢#4+‘MO,œp’2M¼êe뿆w¥ro¬>gP4s2)9;p

但是如何获得NSString格式呢?我的代码中有错误的步骤吗?

EN

回答 1

Stack Overflow用户

发布于 2013-05-31 12:44:21

总是垫上你的纯文本PKCS #1是RSA加密的标准填充。

另外,请注意,使用RSA公钥加密,您只能加密/解密不超过密钥大小的数据(减去一些开销字节)。

公钥加密通常只用于加密密钥(和哈希),然后用于实际有效负载的对称加密(和验证)。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16850544

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档