[英]RSA Bad Padding Exception
I am trying to RSA encrypt data on Android and send it to server(spring). 我正在尝试在Android上对RSA加密数据并将其发送到server(spring)。 getting BadPaddingException :
得到BadPaddingException:
Approach: server send public key in a string, which i convert to PublicKey Object and send data from App after encryption as a string. 方法:服务器以字符串形式发送公钥,我将其转换为PublicKey Object,并在加密后以字符串形式从App发送数据。 server has a private key string , which is converted to PublicKey object and then data is decrypted.
服务器具有私钥字符串,该私钥字符串将转换为PublicKey对象,然后解密数据。
Any Help would be much appreciated. 任何帮助将非常感激。
generation of key : 密钥生成:
public static KeyPair generateKeyPairRSA() {
try {
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(1024, random);
KeyPair keyPair = keyGen.generateKeyPair();
return keyPair;
} catch (Exception e) {
Log.d(TAG,e.getLocalizedMessage());
}
return null;
}
public byte[] RSAEncrypt(final String plain, PublicKey publicKey) throws Exception {
Cipher cipher = Cipher.getInstance(ALGO_RSA);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptedBytes = cipher.doFinal(plain.getBytes());
return encryptedBytes;
}
public static PublicKey loadPublicKey1(String stored) throws Exception{
byte[] data = Base64.decode(stored.getBytes());
X509EncodedKeySpec spec = new X509EncodedKeySpec(data);
KeyFactory fact = KeyFactory.getInstance(ALGO_RSA);
return fact.generatePublic(spec);
}
Server Methods : 服务器方法:
public byte[] decryptRSA(String inputData) throws Exception {
byte[] inputBytes = Base64.decodeBase64(inputData);
PrivateKey key = loadPrivateKey(getPrivateKey());
Cipher cipher1 = Cipher.getInstance("RSA");
cipher1.init(Cipher.DECRYPT_MODE, key);
return cipher1.doFinal(inputBytes);
}
private PrivateKey loadPrivateKey(String key64) throws Exception {
byte[] pkcs8EncodedBytes = Base64.decodeBase64(key64);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pkcs8EncodedBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePrivate(keySpec);
}
Got it Working. 得到它的工作。 So diffrent libs have differenet implementation of Cipher.
因此,不同的库具有不同的Ciphernet实现。 so while calling
所以在打电话时
Cipher.getInstance("RSA/ECB/PKCS1Padding"); Cipher.getInstance( “RSA / ECB / PKCS1Padding”);
Explicitly mention encryption mode and padding. 明确提及加密模式和填充。
Hope it helps somebody. 希望它能帮助到别人。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.