从Objective-c中的模数和指数(以字节为单位)生成RSA公钥

时间:2013-03-14 21:09:15

标签: objective-c openssl rsa modulus exponent

我正在搜索许多试图了解RSA如何运作的网站。

我有一个模量“A89F25A56FA6DA258C8CA8B40427D927B4A1EB4D7EA326BBB12F97DED70AE5E4480FC9C5E8A972177110A1CC318D06D2F8F5C4844AC5FA79A4DC470BB11ED635699C17081B90F1B984F12E92C1C529276D8AF8EC7F28492097D8CD5BECEA16FE4088F6CFAB4A1B42328A1B996F9278B0B7E3311CA5EF856C2F888474B83612A82E4E00D0CD4069A6783140433D50725F”和指数“03”和我有解密在十六进制字节格式化信息。我的问题是:

如何创建公钥? 一旦我有公钥,我必须在base64中编码或公钥是否已准备好解密?

1 个答案:

答案 0 :(得分:3)

经过几天的研究,我终于用OpenSSL做了。我不是C ++方面的专家所以我不确定是否所有字符,常量字符和无符号字符都被正确声明,所以如果有人有更好的想法,请编辑它=)。你必须有lybcrypto.a和libssl.a(在这里你可以找到它们https://github.com/x2on/OpenSSL-for-iPhone)。我用EMV VISA键测试了好几次,然后就可以了。

#include <openssl/opensslv.h>
#include <openssl/rsa.h>
#include <openssl/evp.h>
#include <openssl/bn.h>

@implementation ViewController

-(NSData*) decryptIPKC:(NSString*)ipkc modulus:(NSString*)mod exponent:(NSString*)exp{

NSString * hexString = ipkc;
int hexStringLength= [hexString length] / 2;

//unsigned char enc_bin[144];
unsigned char dec_bin[hexStringLength];
//int enc_len;
int dec_len;
RSA * rsa_pub = RSA_new();


const char *N=[mod UTF8String] ;
const char *E=[exp UTF8String];



char * myBuffer = (char *)malloc((int)[hexString length] / 2 + 1);
bzero(myBuffer, [hexString length] / 2 + 1);
for (int i = 0; i < [hexString length] - 1; i += 2) {
unsigned int anInt;
NSString * hexCharStr = [hexString substringWithRange:NSMakeRange(i, 2)];
NSScanner * scanner = [[NSScanner alloc] initWithString:hexCharStr];
[scanner scanHexInt:&anInt];
myBuffer[i / 2] = (char)anInt;
}

printf("Mybuffer: %s",myBuffer);

if (!BN_hex2bn(&rsa_pub->n, N)) {
printf("NO CARGO EL MODULO");
}
printf(" N: %s\n", N);
printf(" n: %s\n", BN_bn2hex(rsa_pub->n));


if (!BN_hex2bn(&rsa_pub->e, E)) {
printf("NO  CARGO EL EXPONENTE");
}
printf(" E: %s\n", E);
printf(" e: %s\n", BN_bn2hex(rsa_pub->e));

printf("public key size : %d bits\n", RSA_size(rsa_pub));    

/* decrypt */
if ((dec_len = RSA_public_decrypt(hexStringLength, (unsigned char*)myBuffer, dec_bin, rsa_pub,RSA_NO_PADDING))<0) {
printf("NO\n ");
}
printf("decrypted data:\n %s", dec_bin);
print_hex(dec_bin, dec_len);

NSData* data = [NSData dataWithBytes:dec_bin length:sizeof(dec_bin)];

free(myBuffer);

return data;
}
- (void)viewDidLoad {
[super viewDidLoad];
NSString *m= @"Your HEX modulus here";
NSString *e=@"Your HEX exponent";
NSString * hexString= @"Your HEX message here";

NSData *decryptedIPKC= [self decryptIPKC:hexString modulus:m exponent:e];
NSLog(@"ESTE ES EL NSDATA %@", decryptedIPKC.description);
}

@end
相关问题