簡體   English   中英

將 rsa 私鑰分成兩半

[英]divide rsa private key in two halves

我想將 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。 此處介紹的討論類似

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");
        }

     }
}

注意:請查看 SecureRandom on random seed的以下文檔。 特別突出顯示的部分

許多 SecureRandom 實現采用偽隨機數生成器 (PRNG) 的形式,這意味着它們使用確定性算法從真正的隨機種子生成偽隨機序列。 其他實現可能會產生真正的隨機數,而其他實現可能會使用這兩種技術的組合。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM