In my project i am working on AES encryption and Decryption.i have used this algorithm to encrypt and decryption a string and storing the string in the sq-lite database.Now i get that encrypted key from database and try to decryption it but it shows an Exception (pad Block corrupted).I am converting the Encrypted string into the bytes by using
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));}
return data;
}
and getting the correct Bytes but while converted into the String it shows ‘pad block corrupted’.
Thanks in advance.really appreciate if find answer.
my code is
dh=new data_helper(Resy.this);
mac_db=dh.getData();
// getdata=mac_db.toString();
KeyGenerator kgen;
try {
kgen = KeyGenerator.getInstance("AES");
kgen.init(128); // 192 and 256 bits may not be available
// Generate the secret key specs.
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
// Instantiate the cipher
Cipher cipher = Cipher.getInstance("AES");
getdata=mac_db.toString();
// byte g1[]=getdata.getBytes();
// System.out.println(g1);
byte b[]=hexStringToByteArray(getdata);
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] m1=cipher.doFinal(b); // here pad block corrupt exception came.
String originalString_mac = new String(original_macadress);
Toast.makeText(getApplicationContext(),"Original : " +originalString_mac + " " + asHex(original_macadress) , Toast.LENGTH_LONG).show();
you have to do Base64 encoding of it to get proper AES encrypt/decrypt to work.
Do it as follows.
For encrytion : Original String –> Aes encryption > base64 encode —>(encrypted string)
For decryption : encrypted string —> base64 decode > aes decryption —> Original String