RSAPrivateKeySpec javax.crypto.BadPaddingException中的Java RSA密钥:解密错误
我有一个没有Java加密库的RSA代码类。 它起作用了RSAPrivateKeySpec javax.crypto.BadPaddingException中的Java RSA密钥:解密错误,java,encryption,rsa,Java,Encryption,Rsa,我有一个没有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(); Big
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;
}
}
为什么?
抱歉,我的英语不好。输入到
密码。getInstance()
可以有两种形式:
- “算法/模式/填充”或
- “算法”
Cipher.getInstance(“RSA”)代码>您将获得一个默认的填充,并且由于加密未包含填充,因此在尝试删除预期填充时解密失败
尝试以下操作以获得无填充的RSA密码:
Cipher cip = Cipher.getInstance("rsa/ecb/nopadding");
填充的原因(PKCS1-v1_5 fka type 02)是默认的,因为在大多数实际使用中,未添加的RSA是不安全的,很容易被破坏——此外OP的方法比必要的速度慢得多。但这些都不是编程问题,属于另一个堆栈。
Cipher cip = Cipher.getInstance("rsa/ecb/nopadding");