Android上唯一的密钥对生成 [英] Unique Key Pair Generation on Android

查看:415
本文介绍了Android上唯一的密钥对生成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试在android中生成唯一的密钥对.谁能告诉我为什么以下项在第一次被调用时总是产生相同的密钥?

I have been trying to generate unique key pairs in android. Can anyone tell me why the following always produces the same key the first time it is called?

long ltime = System.currentTimeMillis();
    SecureRandom random = null;
    random = new SecureRandom();
    byte[] seed = ByteBuffer.allocate(8).putLong(ltime).array();
    random.nextBytes(seed);
    RSAKeyGenParameterSpec spec = new RSAKeyGenParameterSpec(1024, RSAKeyGenParameterSpec.F4);
    try {
        mKeyPairGenerator.initialize(spec, random);
    } catch (InvalidAlgorithmParameterException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    mKeyPair = mKeyPairGenerator.generateKeyPair();
    mPublicKey = (PublicKey) mKeyPair.getPublic();
    mPrivateKey = (PrivateKey) mKeyPair.getPrivate();

推荐答案

始终生成相同的密钥,因为 SecureRandom 是确定性的,始终会产生相同的结果.只是不要设置种子,这可能是不安全的,因为您可以在参考书目中进行阅读:

Always generate the same key, because SecureRandom with a seed is deterministic and always produce a same result. Just don't set the seed, this can be insecure as you can read on bibliography:

播种SecureRandom可能不安全

种子是用于引导随机数的字节数组 一代.为了产生加密安全的随机数,两者 种子和算法必须是安全的.

A seed is an array of bytes used to bootstrap random number generation. To produce cryptographically secure random numbers, both the seed and the algorithm must be secure.

默认情况下,此类的实例将生成初始种子 使用内部熵源,例如/dev/urandom.这颗种子是 不可预测且适合安全使用.

By default, instances of this class will generate an initial seed using an internal entropy source, such as /dev/urandom. This seed is unpredictable and appropriate for secure use.

只需使用KeyPairGenerator类:

Just use a KeyPairGenerator class:

    KeyPair keys = null;
    try {
        RSAKeyGenParameterSpec spec = new RSAKeyGenParameterSpec(1024, RSAKeyGenParameterSpec.F4);
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(spec);
        keys = keyGen.generateKeyPair();
    } catch (InvalidAlgorithmParameterException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }

    if(keys != null){
        PublicKey mPublicKey = (PublicKey) keys.getPublic();
        PrivateKey mPrivateKey = (PrivateKey) keys.getPrivate();
    }

这篇关于Android上唯一的密钥对生成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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