如何找出iPhone / Objective C上RSA公钥的模数和指数 [英] How to find out the modulus and exponent of RSA Public Key on iPhone/Objective C

查看:254
本文介绍了如何找出iPhone / Objective C上RSA公钥的模数和指数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有可能的方法来找出使用SecKeyGeneratePair(一般的安全框架)创建的公钥的模数和指数?

Is there a possible way to find out the modulus and exponent of the Public Key, created with SecKeyGeneratePair (the Security Framework in general)?

推荐答案

这是我的头,但这里是一个我找到的解决方案(不使用任何外部包)。

Busted my head on this, but here's a solution I've found (without using any external packages).

首先,去苹果的CryptoExercise示例。从那里下载SecKeyWrapper类。该类中有趣的函数是getPublicKeyBits。

First, go to Apple's CryptoExercise example. Download the "SecKeyWrapper" class from there. The interesting function in that class is getPublicKeyBits.

链接到示例:http://developer.apple.com/library/ios/#samplecode/CryptoExercise/Introduction/Intro.html

您将收到的位是包含模数和exp的DER编码(wiki it)公钥。这里是一个代码,将为您解码,很容易:

The bits you will receive is a DER encoded (wiki it) public key containing both the modulus and exp. Here's a code that will decode it for you, pretty easy:

- (NSData *)getPublicKeyExp
{
    NSData* pk = [self getPublicKeyBits];
    if (pk == NULL) return NULL;

    int iterator = 0;

    iterator++; // TYPE - bit stream - mod + exp
    [self derEncodingGetSizeFrom:pk at:&iterator]; // Total size

    iterator++; // TYPE - bit stream mod
    int mod_size = [self derEncodingGetSizeFrom:pk at:&iterator];
    iterator += mod_size;

    iterator++; // TYPE - bit stream exp
    int exp_size = [self derEncodingGetSizeFrom:pk at:&iterator];

    return [pk subdataWithRange:NSMakeRange(iterator, exp_size)];
}

- (NSData *)getPublicKeyMod
{
    NSData* pk = [self getPublicKeyBits];
    if (pk == NULL) return NULL;

    int iterator = 0;

    iterator++; // TYPE - bit stream - mod + exp
    [self derEncodingGetSizeFrom:pk at:&iterator]; // Total size

    iterator++; // TYPE - bit stream mod
    int mod_size = [self derEncodingGetSizeFrom:pk at:&iterator];

    return [pk subdataWithRange:NSMakeRange(iterator, mod_size)];
}

- (int)derEncodingGetSizeFrom:(NSData*)buf at:(int*)iterator
{
    const uint8_t* data = [buf bytes];
    int itr = *iterator;
    int num_bytes = 1;
    int ret = 0;

    if (data[itr] > 0x80) {
        num_bytes = data[itr] - 0x80;
        itr++;
    }

    for (int i = 0 ; i < num_bytes; i++) ret = (ret * 0x100) + data[itr + i];

    *iterator = itr + num_bytes;
    return ret;
}

这篇关于如何找出iPhone / Objective C上RSA公钥的模数和指数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆