Bad Padding Exception - java

I am trying a program to first encrypt and decrypt a string and in between encoding it into 64base and then decoding it into 64base(this is required). But I am getting the below error. What is the possible fix?
Exception in thread "main" javax.crypto.BadPaddingException: Decryption error
at java.base/sun.security.rsa.RSAPadding.unpadV15(RSAPadding.java:378)
at java.base/sun.security.rsa.RSAPadding.unpad(RSAPadding.java:290)
at java.base/com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:366)
at java.base/com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:392)
at java.base/javax.crypto.Cipher.doFinal(Cipher.java:2202)
at CryptographyExample.decrypt(encryt_decrypt.java:53)
at CryptographyExample.main(encryt_decrypt.java:88)
My code
class CryptographyExamples {
private static final String ALGORITHM = "RSA";
public static byte[] encrypt(byte[] publicKey, byte[] inputData) throws Exception {
PublicKey key = KeyFactory.getInstance(ALGORITHM).generatePublic(new X509EncodedKeySpec(publicKey));
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encryptedBytes = cipher.doFinal(inputData);
return encryptedBytes;
}
public static byte[] decrypt(byte[] privateKey, byte[] inputData) throws Exception {
PrivateKey key = KeyFactory.getInstance(ALGORITHM).generatePrivate(new PKCS8EncodedKeySpec(privateKey));
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decryptedBytes = cipher.doFinal(inputData);
return decryptedBytes;
}
public static KeyPair generateKeyPair() throws NoSuchAlgorithmException, NoSuchProviderException {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM);
SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
// 512 is keysize
keyGen.initialize(512, random);
KeyPair generateKeyPair = keyGen.generateKeyPair();
return generateKeyPair;
}
public static MessageDigest md;
public static void main(String[] args) throws Exception {
String originalMessage = "The message to be encrypted and sent";
md = MessageDigest.getInstance("SHA-256");
KeyPair generateKeyPair = generateKeyPair();
byte[] publicKey = generateKeyPair.getPublic().getEncoded();
byte[] privateKey = generateKeyPair.getPrivate().getEncoded();
byte[] encryptedData = encrypt(publicKey, originalMessage.getBytes());
byte[] shaEncryptedData = md.digest(encryptedData);
String shaEncryption64 = Base64.getEncoder().encodeToString(shaEncryptedData);
byte[] decryptedData = decrypt(privateKey, Base64.getDecoder().decode(shaEncryption64));
System.out.println("Decrypted Message: " + new String(decryptedData));
}
}

Related

javax.crypto.BadPaddingException: Decryption error and also Message larger than modulus

Below I try to send message in multicast socket through group and to provide encryption:
Encrypt the data with the symmetric key
Encrypt the symmetric key with rsa
send the encrypted key and the data
Decrypt the encrypted symmetric key with rsa
decrypt the data with the symmetric key
But I am getting this error
javax.crypto.BadPaddingException: Decryption error at java.base/sun.security.rsa.RSAPadding.unpadV15(RSAPadding.java:378) at java.base/sun.security.rsa.RSAPadding.unpad(RSAPadding.java:290) at java.base/com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:366) at java.base/com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:392) at java.base/javax.crypto.Cipher.doFinal(Cipher.java:2208) at Security.RSADecryption(Symmetra.java:63) at ReadThread.run(Symmetra.java:202) at java.base/java.lang.Thread.run(Thread.java:835)
I think I did not understood encryption decryption properly.
See below for the code:
class Security
{
public static SecretKey createAESKey() throws Exception
{
KeyGenerator generator = KeyGenerator.getInstance("AES");
generator.init(128); // The AES key size in number of bits
SecretKey key = generator.generateKey();
return key;
}
public static KeyPair generateRSAkeyPair() throws Exception
{
//SecureRandom secureRandom = new SecureRandom();
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
//KeyGenerator keyGenerator = KeyGenerator.getInstance("RSA");
keyPairGenerator.initialize(4096);
KeyPair pair = keyPairGenerator.generateKeyPair();
return pair;
}
public static byte[] AESEncryption(String plaintext, SecretKey secKey) throws Exception
{
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE,secKey);
byte[] cipherText = cipher.doFinal(plaintext.getBytes());
return cipherText;
}
public static byte[] RSAEncryption(PublicKey publicKey, SecretKey key) throws Exception
{
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
//cipher.update(plaintext.getBytes());
byte [] encryptedKey = cipher.doFinal(key.getEncoded());
System.out.println(encryptedKey.length);
return encryptedKey;
}
public static byte[] RSADecryption(byte[] encryptedKey, PrivateKey privateKey) throws Exception
{
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte check[] = cipher.doFinal(encryptedKey);
return cipher.doFinal(encryptedKey);
}
public static String AESDecryption(byte[] decryptedKey, byte[] text) throws Exception
{
SecretKey originalKey = new SecretKeySpec(decryptedKey , 0, decryptedKey.length, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, originalKey);
byte[] plaintext = cipher.doFinal(text);
return new String(plaintext);
}
public static KeyPair generate() throws Exception
{
KeyPair keyPair = generateRSAkeyPair();
return keyPair;
}
}
public class TestDemo extends Security
{
public static void main(String args[])
{
KeyPair keyPair = generate();
SecretKey key = createAESKey();
byte[] cipherText = AESEncryption(message,key);
byte[] encryptedKey = RSAEncryption(keyPair.getPublic(), key);
DatagramPacket datagram = new
DatagramPacket(cipherText,cipherText.length,group,port); // It carries encrpyted message
// It carries symmetric key encrypted by RSA
DatagramPacket datagram2 = new
DatagramPacket(encryptedKey,encryptedKey.length,group,port);
socket.send(datagram);
socket.send(datagram2);
}
}
class ReadThread extends Security
{
KeyPair keyPair;
SecretKey key;
try
{
keyPair = generate();
key = createAESKey();
byte[] buffer = new byte[ReadThread.MAX_LEN];
DatagramPacket datagram = new DatagramPacket(buffer,buffer.length,group,port);
byte[] keyBuffer = new byte[512];
DatagramPacket datagram2 = new
DatagramPacket(keyBuffer,keyBuffer.length,group,port);
String message;
try
{
socket.receive(datagram);
socket.receive(datagram2);
byte[] decryptKey = RSADecryption(keyBuffer,keyPair.getPrivate());
String decryptText = AESDecryption(decryptKey, buffer);
message = decryptText;
if(!message.startsWith(Symmetra.name))
System.out.println(message);
}
catch(IOException e)
{
System.out.println("Socket closed!");
}
}
}

Use Java Cipher equivalent in Flutter

a i need help to decrypt values generated in Android Java App on Flutter.
I need a class who this but in Dart/Flutter:
public class TrippleDes {
// public static String ALGO = "DESede/CBC/PKCS7Padding";
public static String ALGO = "DESede/ECB/PKCS7Padding";
public static String _encrypt(String message, String secretKey) throws Exception {
Cipher cipher = Cipher.getInstance(ALGO);
cipher.init(Cipher.ENCRYPT_MODE, getSecreteKey(secretKey));
byte[] plainTextBytes = message.getBytes("UTF-8");
byte[] buf = cipher.doFinal(plainTextBytes);
byte[] base64Bytes = Base64.encode(buf, Base64.DEFAULT);
String base64EncryptedString = new String(base64Bytes);
return base64EncryptedString;
}
public static String _decrypt(String encryptedText, String secretKey) throws Exception {
byte[] message = Base64.decode(encryptedText.getBytes(), Base64.DEFAULT);
Cipher decipher = Cipher.getInstance(ALGO);
decipher.init(Cipher.DECRYPT_MODE, getSecreteKey(secretKey));
byte[] plainText = decipher.doFinal(message);
return new String(plainText, "UTF-8");
}
public static SecretKey getSecreteKey(String secretKey) throws Exception {
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] digestOfPassword = md.digest(secretKey.getBytes("utf-8"));
byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
SecretKey key = new SecretKeySpec(keyBytes, "DESede");
return key;
}
}

encryption/decryption by Aes not working

this code encryption/decryption dynamic data that entered by user:
private final String characterEncoding = "UTF-8";
private final String cipherTransformation = "AES/CBC/PKCS5Padding";
private final String aesEncryptionAlgorithm = "AES";
public String encrypt(String plainText, String key) throws UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException{
byte[] plainTextbytes = plainText.getBytes(characterEncoding);
byte[] keyBytes = getKeyBytes(key);
return Base64.encodeToString(encrypt(plainTextbytes,keyBytes, keyBytes), Base64.DEFAULT);
}
public String decrypt(String encryptedText, String key) throws KeyException, GeneralSecurityException, GeneralSecurityException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, IOException {
byte[] cipheredBytes = Base64.decode(encryptedText, Base64.DEFAULT);
byte[] keyBytes = getKeyBytes(key);
return new String(decrypt(cipheredBytes, keyBytes, keyBytes), characterEncoding);
}
public byte[] decrypt(byte[] cipherText, byte[] key, byte [] initialVector) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, InvalidParameterSpecException {
Cipher cipher = Cipher.getInstance(cipherTransformation);
SecretKeySpec secretKeySpecy = new SecretKeySpec(key, aesEncryptionAlgorithm);
IvParameterSpec ivParameterSpec = new IvParameterSpec(initialVector);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpecy, ivParameterSpec);
cipherText = cipher.doFinal(cipherText);
return cipherText;
}
public byte[] encrypt(byte[] plainText, byte[] key, byte [] initialVector) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException
{
Cipher cipher = Cipher.getInstance(cipherTransformation);
SecretKeySpec secretKeySpec = new SecretKeySpec(key, aesEncryptionAlgorithm);
IvParameterSpec ivParameterSpec = new IvParameterSpec(initialVector);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
plainText = cipher.doFinal(plainText);
return plainText;
}
private byte[] getKeyBytes(String key) throws UnsupportedEncodingException{
byte[] keyBytes= new byte[16];
byte[] parameterKeyBytes= key.getBytes(characterEncoding);
System.arraycopy(parameterKeyBytes, 0, keyBytes, 0, Math.min(parameterKeyBytes.length, keyBytes.length));
return keyBytes;
}
but for some data (example : u8/OgSllm2agXlDrGcdqWg== ) decryption is not working and execution catch:
javax.crypto.BadPaddingException: error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt
or for some data get different error , example : SmQ0YMiq+SHn34m8h3gWw==
get this error :
java.lang.IllegalArgumentException: bad base-64
Try with this code and download library commons-codec-1.11-bin from the below link and add it to build path
enter link description here
Java Code:
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
public class AES {
public static String encrypt(String key, String initVector, String value) {
try {
IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(value.getBytes());
System.out.println("encrypted string: "
+ Base64.encodeBase64String(encrypted));
return Base64.encodeBase64String(encrypted);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static String decrypt(String key, String initVector, String encrypted) {
try {
IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted));
return new String(original);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static void main(String[] args) {
String key = "Bar12345Bar12345"; // 128 bit key
String initVector = "RandomInitVector"; // 16 bytes IV
System.out.println(decrypt(key, initVector,
encrypt(key, initVector, "Hello World")));
}
}

RSA Bad Padding Exception

I am trying to RSA encrypt data on Android and send it to server(spring).
getting 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.
server has a private key string , which is converted to PublicKey object and then data is decrypted.
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.
so while calling
Cipher.getInstance("RSA/ECB/PKCS1Padding");
Explicitly mention encryption mode and padding.
Hope it helps somebody.

Java RSA Encryption/Decryption issues

I need code that can encrypt/decrypt data using RSA by BouncyCastle Java API. I implemented it but got following exception:
javax.crypto.BadPaddingException: unknown block type in following code.
Here's the code:
public class rsa {
private PrivateKey rsaPrivate;
private PublicKey rsapublic;
private Cipher cipher=null;
private final String ALGORITHM = "RSA";
private final String PROVIDER = "BC";
public rsa() throws NoSuchAlgorithmException, NoSuchPaddingException, NoSuchProviderException
{
this.init();
}
public void init() throws NoSuchAlgorithmException, NoSuchPaddingException, NoSuchProviderException
{
Security.addProvider(new BouncyCastleProvider());
KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM,PROVIDER);
keyGen.initialize(1024);
KeyPair keyPair = keyGen.generateKeyPair();
this.setRsaPrivate(keyPair.getPrivate()) ;
this.setRsapublic(keyPair.getPublic());
}
********* Getter**(){} AND **Setter**(){} methods are removed **********
public String encryption(String Message) throws InvalidKeyException,IllegalBlockSizeException,
BadPaddingException, NoSuchAlgorithmException,
NoSuchProviderException, NoSuchPaddingException,
UnsupportedEncodingException
{
cipher=Cipher.getInstance("RSA/ECB/PKCS1Padding",PROVIDER);
cipher.init(Cipher.ENCRYPT_MODE,this.getRsapublic());
byte[] encryptedMsg = cipher.doFinal(Message.getBytes());
return new String(encryptedMsg);
}
public String decryption(String encryptedMsg) throws InvalidKeyException, IllegalBlockSizeException,
BadPaddingException, UnsupportedEncodingException,
NoSuchAlgorithmException, NoSuchProviderException,
NoSuchPaddingException
{
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding",PROVIDER);
cipher.init(Cipher.DECRYPT_MODE,this.getRsaPrivate());
byte[] dectyptedText = cipher.doFinal(encryptedMsg.getBytes());
return new String(dectyptedText);
}
public static void main(String args[]) throws Exception
{
rsa r=new rsa();
System.out.println("Test1 encrypt normal: "+Base64.encodeBase64String(r.encryption("123456").getBytes()));
System.out.println("Test2 decrypt normal: "+r.decryption(r.encryption("123456")));
}
}
*OUTPUT**: Test1 encrypt normal:
uXpqwit/bNH9GUpCPoL+7pjVhOYfQT95ZHCHRoBntfYuKhV9cnQUeSe2df1oTdp45JZFG9uohGssnMP2‌​BP9Lm6+xwxprQi7t2n3mjoLOTj+e+2rc2/hKlwhoHIpEmO6O7SWeQh+05PIhP9YnPOM97VKGfu/oXFj12‌​84pC9s0smM= Exception in thread "main" javax.crypto.BadPaddingException: unknown block type at org.bouncycastle.jce.provider.JCERSACipher.engineDoFinal(Unknown Source) at javax.crypto.Cipher.doFinal(DashoA13*..) at com.crypto.rsa.decryption(rsa.java:85) >>>>>>>>>>>>>>>>>>>>>got error here in method decryption cipher.doFinal(encryptedMsg.getBytes())
Finally got output
public class RSAUTIL
{
String ALGORITHM_USED = "RSA";
String PROVIDER = "BC";
private KeyPair key;
public RSAUTIL() throws NoSuchAlgorithmException
{
this.init();
this.generateKey();
}
public void init()
{
Security.addProvider(new BouncyCastleProvider());
}
public KeyPair generateKey() throws NoSuchAlgorithmException
{
KeyPairGenerator keyGen = null;
try {
keyGen = KeyPairGenerator.getInstance(ALGORITHM_USED, PROVIDER);
}catch (NoSuchProviderException e){e.printStackTrace();}
keyGen.initialize(1024);
key = keyGen.generateKeyPair();
return key;
}
public PublicKey getpublickey()
{
return key.getPublic();
}
public PrivateKey getprivatekey()
{
return key.getPrivate();
}
public byte[] encrypt(byte[] text, PublicKey key) throws Exception
{
byte[] cipherText = null;
try
{
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding",PROVIDER);
cipher.init(Cipher.ENCRYPT_MODE, key);
cipherText = cipher.doFinal(text);
}catch (Exception e){throw e;}
return cipherText;
}
public String encrypt(String text, PublicKey key) throws Exception
{
String encryptedText;
try
{ byte[] cipherText = encrypt(text.getBytes(),key);
encryptedText = encodeToBASE64(cipherText);
}catch (Exception e){throw e;}return encryptedText;
}
public byte[] decrypt(byte[] text, PrivateKey key) throws Exception
{
byte[] dectyptedText = null;
try
{
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding",PROVIDER);
cipher.init(Cipher.DECRYPT_MODE,key);
dectyptedText = cipher.doFinal(text);
}catch (Exception e){throw e;}
return dectyptedText;
}
public String decrypt(String text, PrivateKey key) throws Exception
{
String result;
try
{ byte[] dectyptedText = decrypt(decodeToBASE64(text),key);
result = new String(dectyptedText);
}catch (Exception e){throw e;}
return result;
}
public String getKeyAsString(Key key)
{
byte[] keyBytes = key.getEncoded();
BASE64Encoder b64 = new BASE64Encoder();
return b64.encode(keyBytes);
}
public PrivateKey getPrivateKeyFromString(String key) throws Exception
{
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_USED);
BASE64Decoder b64 = new BASE64Decoder();
EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(b64.decodeBuffer(key));
PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
return privateKey;
}
public PublicKey getPublicKeyFromString(String key) throws Exception
{
BASE64Decoder b64 = new BASE64Decoder();
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_USED);
EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(b64.decodeBuffer(key));
PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
return publicKey;
}
private String encodeToBASE64(byte[] bytes)
{
BASE64Encoder b64 = new BASE64Encoder();
return b64.encode(bytes);
}
private byte[] decodeToBASE64(String text) throws IOException
{
BASE64Decoder b64 = new BASE64Decoder();
return b64.decodeBuffer(text);
}
public static void main(String[] args) throws Exception {
RSAUTIL rsa= new RSAUTIL();
System.out.println(rsa.decrypt(rsa.encrypt("123",
rsa.getPublicKeyFromString(rsa.getKeyAsString(rsa.getpublickey()))),
rsa.getPrivateKeyFromString(rsa.getKeyAsString(rsa.getprivatekey()))));
}
}
OUTPUT: 123

Categories

Resources