gpt4 book ai didi

java - 将 rsa 私钥分成两半

转载 作者:行者123 更新时间:2023-12-01 17:24:16 24 4
gpt4 key购买 nike

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

}
}

注意:请检查以下 SecureRandom 文档 random seed 。特别是突出显示的部分

Many SecureRandom implementations are in the form of a pseudo-random number generator (PRNG), which means they use a deterministic algorithm to produce a pseudo-random sequence from a true random seed. Other implementations may produce true random numbers, and yet others may use a combination of both techniques.

关于java - 将 rsa 私钥分成两半,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61233658/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com