我正在尝试从模数和私有/公共指数重建 RSA 密钥对。比较编码的私钥时,转换对于公钥正确,但对于私钥则失败。
当使用此重建私钥/公钥对进行加密时,它在 Java 中可以工作(!),但是当在 PHP 中使用重建密钥对时,解密部分失败(加密正在工作),所以在我看来,重建私钥是不同的到“原始”私钥。
仅供参考:使用“原始”密钥对,PHP 中一切正常。
所以我的问题是:如何从(BigInteger)模数和私有指数中检索“原始”私钥?
编辑:最后查看我的最终编辑
我的示例代码显示了公钥与重建密钥的相等性,并且私钥是不同的:
Rebuilding of a RSA PrivateKey from modulus & exponent
privateKey equals rebuild: false
publicKey equals rebuild: true
代码:
import java.math.BigInteger;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.util.Arrays;
public class RebuildRSAPrivateKey {
public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException {
System.out.println("Rebuilding of a RSA PrivateKey from modulus & exponent");
// rsa key generation
KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA");
//kpGen.initialize(2048, new SecureRandom());
kpGen.initialize(2048, new SecureRandom());
KeyPair keyPair = kpGen.generateKeyPair();
// private key
PrivateKey privateKey = keyPair.getPrivate();
// get modulus & exponent
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) privateKey;
BigInteger modulus = rsaPrivateKey.getModulus();
BigInteger privateExponent = rsaPrivateKey.getPrivateExponent();
}
}
编辑:以下程序将显示从编码密钥派生的 RSA 私钥/公钥对可以恢复,并且加密和解密可以在 Java 和 PHP 中进行。密钥是不安全的RSA 512 位密钥并经过 Base64 解码。
然后从模数和私有/公共指数派生出相同的密钥,并且加密/解密在 Java 中有效,但在 PHP 中无效。
这就是为什么我想从模数和指数中获取“原始”RSA 密钥,感谢您的好意帮助。
蛊毒传说