【发布时间】:2018-04-21 06:49:21
【问题描述】:
我有一个没有 Java 加密库的 RSA 代码类。 它有效。
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.Random;
public class RSA {
public static RSAKeyPair generateKeyPair(int keysize) {
Random rnd = new SecureRandom();
BigInteger p = new BigInteger(keysize / 2, 100, rnd);
BigInteger q = new BigInteger(keysize / 2, 100, rnd);
BigInteger n = p.multiply(q);
BigInteger phi = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
BigInteger e;
do {
e = new BigInteger(phi.bitLength(), rnd);
} while (e.compareTo(BigInteger.ONE) <= 0 || e.compareTo(phi) >= 0 || !e.gcd(phi).equals(BigInteger.ONE));
BigInteger d = e.modInverse(phi);
return new RSAKeyPair(new RSAPublicKey(e, n), new RSAPrivateKey(d, n), n);
}
public static BigInteger encrypt(BigInteger m, RSAPublicKey key) {
return m.modPow(key.getPublicExponent(), key.getModulus());
}
public static BigInteger decrypt(BigInteger c, RSAPrivateKey key) {
return c.modPow(key.getPrivateExponent(), key.getModulus());
}
}
class RSAPublicKey {
private BigInteger e;
private BigInteger n;
public RSAPublicKey(BigInteger e, BigInteger n) {
this.e = e;
this.n = n;
}
public BigInteger getPublicExponent() {
return e;
}
public BigInteger getModulus() {
return n;
}
}
class RSAPrivateKey {
private BigInteger d;
private BigInteger n;
public RSAPrivateKey(BigInteger d, BigInteger n) {
this.d = d;
this.n = n;
}
public BigInteger getPrivateExponent() {
return d;
}
public BigInteger getModulus() {
return n;
}
}
class RSAKeyPair {
private RSAPublicKey pub;
private RSAPrivateKey priv;
private BigInteger modulus;
public RSAKeyPair(RSAPublicKey pub, RSAPrivateKey priv, BigInteger modulus) {
this.pub = pub;
this.priv = priv;
this.modulus = modulus;
}
public RSAPublicKey getPublicKey() {
return pub;
}
public RSAPrivateKey getPrivateKey() {
return priv;
}
public BigInteger getModulus() {
return modulus;
}
}
但是,当我从 RSAPrivateKeySpec 创建 Java 库 PrivateKey 时,使用类中的 RSAPrivateKey 的模数和指数,并使用 java 加密库 a 和加密的 BigInteger 类进行加密,它会抛出 javax.crypto.BadPaddingException: Decryption error。
这里:
RSAKeyPair pair = generateKeyPair(1024);
BigInteger encrypted = encrypt(new BigInteger("123456789"), pair.getPublicKey());
KeyFactory factory = KeyFactory.getInstance("RSA");
RSAPrivateKeySpec privSpec = new RSAPrivateKeySpec(pair.getPrivateKey().getModulus(), pair.getPrivateKey().getPrivateExponent());
PrivateKey priv = factory.generatePrivate(privSpec);
Cipher cip = Cipher.getInstance("RSA");
cip.init(Cipher.DECRYPT_MODE, priv);
System.out.println(new BigInteger(cip.doFinal(encrypted.toByteArray())));
为什么?
对不起我的英语不好
【问题讨论】:
标签: java encryption rsa