我想将RSA私钥分为两半,并将它们存储在两个不同的地方,我该怎么办?

public GenerateKeys(int keylength) throws NoSuchAlgorithmException, NoSuchProviderException {
    keylength=512;
    this.keyGen = KeyPairGenerator.getInstance("RSA");
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    this.keyGen.initialize(keylength, random);
}

最佳答案

这是一个示例,它将您的私钥分为两个部分,D1和D2。类似于here的讨论

import java.security.KeyPair;
import java.security.KeyFactory;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.EncodedKeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

public class OnetimePad{

    public static byte[] xor(byte[] key, byte[] rand){
        if(key.length != rand.length){
            return null;
        }
        byte[] ret = new byte[key.length];
        for(int i =0; i < key.length; i++){
            ret[i] = (byte)((key[i] ^ rand[i]) );
        }

        return ret;
    }

     public static void main(String []args) throws Exception{
        SecureRandom random = new SecureRandom();


        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(1024);
        KeyPair keypair = keyGen.genKeyPair();
        PrivateKey privateKey = keypair.getPrivate();
        byte[] privateKeyBytes = privateKey.getEncoded();

        //Private Key Part 1
        byte[] D1 = new byte[privateKeyBytes.length];
        random.nextBytes(D1);

        //Private Key Part 2
        byte[] D2 = xor(privateKeyBytes, D1);

        //now D1 and D2 are split parts of private keys..

        //Let's verify if we could reproduce them back
        byte[] privateKeyByesTmp = xor(D2, D1);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyByesTmp);
        PrivateKey privateKey2 = keyFactory.generatePrivate(privateKeySpec);
        boolean same = privateKey.equals(privateKey2);
        if(same){
            System.out.println("Key loaded successfully");
        }else{
            System.out.println("Ooops");
        }

     }
}


注意:
请检查random seed上SecureRandom的以下文档。特别强调的部分


许多SecureRandom实现都采用伪随机数生成器(PRNG)的形式,这意味着它们使用确定性算法从真实的随机种子生成伪随机序列。其他实现可能会产生真正的随机数,而其他实现可能会同时使用这两种技术。

07-28 00:47