gpt4 book ai didi

java - 如何从 RSAPrivateKey 获取 RSAPrivateCrtKey?

转载 作者:行者123 更新时间:2023-11-30 06:06:52 28 4
gpt4 key购买 nike

我有一个 java.security.interfaces.RSAPrivateKey 和相应的 java.security.interfaces.RSAPublicKey 包含(仅)模数、私有(private)指数和公共(public)指数。

如果我对 RSA 的理解正确,应该可以恢复 java.security.interfaces.RSAPrivateCrtKey(用于 CRT key )的数字。

如果是这样,我该怎么做? (我假设已经有一些实现)。

最佳答案

这样做是可以的,而且有一个比较快的算法可以找到参数。下面是一些说明该算法的 Java 代码。

下面的代码是我对 Chapter 8 of the Handbook of Applied Cryptography 中指定算法的实现。 ,作者 A. Menezes、P. van Oorschot 和 S. Vanstone,CRC 出版社,1996 年,第 8.2.2(i) 节:

enter image description here

/**
* Find a factor of n by following the algorithm outlined in Handbook of Applied Cryptography, section
* 8.2.2(i). See https://cacr.uwaterloo.ca/hac/about/chap8.pdf.
*
*/

private static BigInteger findFactor(BigInteger e, BigInteger d, BigInteger n) {
BigInteger edMinus1 = e.multiply(d).subtract(BigInteger.ONE);
int s = edMinus1.getLowestSetBit();
BigInteger t = edMinus1.shiftRight(s);

for (int aInt = 2; true; aInt++) {
BigInteger aPow = BigInteger.valueOf(aInt).modPow(t, n);
for (int i = 1; i <= s; i++) {
if (aPow.equals(BigInteger.ONE)) {
break;
}
if (aPow.equals(n.subtract(BigInteger.ONE))) {
break;
}
BigInteger aPowSquared = aPow.multiply(aPow).mod(n);
if (aPowSquared.equals(BigInteger.ONE)) {
return aPow.subtract(BigInteger.ONE).gcd(n);
}
aPow = aPowSquared;
}
}

}

public static RSAPrivateCrtKey createCrtKey(RSAPublicKey rsaPub, RSAPrivateKey rsaPriv) throws NoSuchAlgorithmException, InvalidKeySpecException {

BigInteger e = rsaPub.getPublicExponent();
BigInteger d = rsaPriv.getPrivateExponent();
BigInteger n = rsaPub.getModulus();
BigInteger p = findFactor(e, d, n);
BigInteger q = n.divide(p);
if (p.compareTo(q) > 0) {
BigInteger t = p;
p = q;
q = t;
}
BigInteger exp1 = d.mod(p.subtract(BigInteger.ONE));
BigInteger exp2 = d.mod(q.subtract(BigInteger.ONE));
BigInteger coeff = q.modInverse(p);
RSAPrivateCrtKeySpec keySpec = new RSAPrivateCrtKeySpec(n, e, d, p, q, exp1, exp2, coeff);
KeyFactory kf = KeyFactory.getInstance("RSA");
return (RSAPrivateCrtKey) kf.generatePrivate(keySpec);

}

关于java - 如何从 RSAPrivateKey 获取 RSAPrivateCrtKey?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43136036/

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