在Objective-C中使用给定的模数和指数值进行RSA加密

时间:2014-03-24 10:51:17

标签: objective-c rsa

我有一个模数和指数,我必须使用公钥RSA加密明文。

如何使用Objective-C中给定的模数和指数值生成长度为2048位的公钥。 我已经尝试过Openssl,但它正在抛出异常" 要解密的数据超过了256字节模数的最大值"

以下是我尝试过的代码。我没有找到任何将密钥大小设置为2048的选项。

-(NSString*)performRSAEncryptionForData:(NSString *)plaintext withModulus:(NSString*)mod andExponent:(NSString*)exp{

//plaintext = @"abcd";

NSMutableString *hexMod = [NSMutableString string];
NSMutableString *hexExp = [NSMutableString string];
const char* utf8Mod = [mod UTF8String];
const char* utf8Exp = [exp UTF8String];

while ( *utf8Mod ) [hexMod appendFormat:@"%02X" , *utf8Mod++ & 0x00FF];
while ( *utf8Exp ) [hexExp appendFormat:@"%02X" , *utf8Exp++ & 0x00FF];

const char *plain = [plaintext UTF8String];

//char crip[]="";
RSA * pubkey = RSA_new();
BIGNUM * modul = BN_new();
BIGNUM * expon = BN_new();

BN_hex2bn(&modul, [hexMod UTF8String]);
BN_hex2bn(&expon, [hexExp UTF8String]);


pubkey->n = modul;
pubkey->e = expon;

int rsa_length = RSA_size(pubkey);
unsigned char *crip[rsa_length];// =(unsigned char*)malloc( rsa_length ) ;
//unsigned char *crip = (unsigned char*)malloc(rsa_length);


NSString *s= [[NSString alloc] init];
NSData* data;

int iRsaRet = RSA_public_encrypt(strlen(plain), (const unsigned char *) plain,  (unsigned char *)crip, pubkey, RSA_PKCS1_OAEP_PADDING );
if (iRsaRet<=0)
{
    NSLog(@"ERROR encrypt");
    s= @"";
}
else
{
    NSLog(@"%lu",sizeof(crip));
    data = [NSData dataWithBytes:crip length:sizeof(crip)];
    //data = [NSData dataWithBytes:(const void *)crip length:256];
    s=[data base64Encoding];
    NSLog(@"Generated Token: %@",s);


}

return s;

}

0 个答案:

没有答案