作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想将 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/
我是一名优秀的程序员,十分优秀!