Hello everyone i have string encrypted in PHP by openssl_encrypt with algorithm 'aes-256-cbc'
Key: C4E30455853D4949A8E91B2C366BE9DE
Vector: 5686044872102713
Encrypted string: ak9YSTd6RXU5TENocUxQUGxieVhpZ3VqSlFiQUdndGZrbVJvbEliTGZjZz0=
And here is my Java function for decrypt:
public static String Decrypt_AES_FromBase64(String AEncryptedText, String AKey32Bytes, String AVectorNum16Bytes) {
try {
byte[] vEncryptedBytes = Base64.getDecoder().decode(AEncryptedText);
Key SecretKey = new SecretKeySpec(AKey32Bytes.getBytes(), "AES");
IvParameterSpec vSpec = new IvParameterSpec(AVectorNum16Bytes.getBytes());
Cipher vCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
vCipher.init(Cipher.DECRYPT_MODE, SecretKey, vSpec);
return new String(vCipher.doFinal(vEncryptedBytes));
} catch (Exception e) {
Common.mContext.getLogger().log(e.toString());
return "";
}
}
When i try to decrypt i have error:
javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher
Can somebody tell what the wrong?
The encrypted string AKey32Bytes is double Base64 encoded.
Instead of AKey32Bytes.getBytes() you need to double Base64 decode the encrypted data to binary.
Encrypted string:
ak9YSTd6RXU5TENocUxQUGxieVhpZ3VqSlFiQUdndGZrbVJvbEliTGZjZz0=
After one Base64 decode:
jOXI7zEu9LChqLPPlbyXigujJQbAGgtfkmRolIbLfcg=
After a second Base64 decode (displayed in hex because it is not binary):
8CE5C8EF312EF4B0A1A8B3CF95BC978A0BA32506C01A0B5F9264689486CB7DC8
That is what needs to be provided to the decryption function.
The decrypted result is:
(in hex) 257531362A2179704B40577255516272
(in ASCII): "%u16*!ypK#WrUQbr" (all valid ASCII characters)
Note: there is a full block of PKCS#7 padding (in hex): 10101010101010101010101010101010
As much as it pains me to say this, from the correct padding I can assume the decryption was successful.
See Cryptomathic AES CALCULATOR
Related
I am trying to decrypt the ResponseText variable which i get from an API. I am getting the following error.
Exception in thread "main" javax.crypto.IllegalBlockSizeException: Input length must be
multiple of 16 when decrypting with padded cipher
Below is my code snippet for decrypting the response. The Decrytpt method is throwing the error.
public static String decrypt(String encryptedText) throws Exception
{
Key key = generateKey();
Cipher chiper = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec ivspec = new IvParameterSpec(iv);
chiper.init(Cipher.DECRYPT_MODE, key, ivspec);
byte[] encVal = chiper.doFinal(encryptedText.getBytes("UTF-8"));
Base64.Encoder base64Encoder = Base64.getEncoder();
String decryptedValue = base64Encoder.encodeToString(encVal);
String decryptedString= new String("");
return decryptedString;
}
I have not posted the actual encrypted value here as the length of the encrypted value is too high. I am new to Java. Thanks in advance.
You should probably base 64 decode the ciphertext, decrypt the binary ciphertext and then decode the resulting plaintext to UTF-8.
You haven't correctly reversed the encryption routine (encode UTF-8, encrypt, encode base64), in other words.
There is a generateKey() for the decryption; unless it returns a static value (and doesn't generate one, as the method name implies) decryption will likely fail. So either the name is wrong, or the decryption.
The IV doesn't seem to be included with the ciphertext either, which will mean that that's the next problem to deal with.
Finally, you will want to know how to handle exceptions for encryption / decryption routines.
Need help with openssl, What would be the openssl equivalent of the below java method?
private static String decryptString(String value, String myKey) {
MessageDigest sha = null;
SecretKeySpec secretKey = null;
try {
byte[] key = myKey.getBytes("UTF-8");
sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16); // use only first 128 bit
secretKey = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return (new String(cipher.doFinal(Base64.decodeBase64(value))));
} catch (Exception e) {
System.out.println("Error while decrypting: " + e.toString());
}
return null;
}
The function is digesting a string (myKey) using SHA-1 and then using the first 16 bytes of the resulting digest as the key for an AES128-ECB decryption operation. Before decryption, the ciphertext is first base64 decoded.
To digest a string using SHA-1 use the code here:
https://wiki.openssl.org/index.php/EVP_Message_Digests
That code actually uses SHA-256. To make it do SHA-1 instead replace the instance of EVP_sha256() with EVP_sha1(). The first 16 bytes of the result is your "key".
Next the input "value" is base64 decoded. There is some sample code to do that with OpenSSL here:
http://www.ioncannon.net/programming/122/howto-base64-decode-with-cc-and-openssl/
Finally, to do the AES-ECB decryption operation use the code here:
https://wiki.openssl.org/index.php/EVP_Symmetric_Encryption_and_Decryption#Decrypting_the_Message
That code is using AES256-CBC. To make it do AES128-ECB instead replace the instance of EVP_aes_256_cbc() with EVP_aes_128_ecb(). The key argument is as you calculated above. The iv argument is just NULL for ECB. The ciphertext is the base64 decoded data that you calculated above. Note that the "PKCS5PADDING" part of the Java code is the default in OpenSSL anyway, so nothing special needs to be done for that.
The plaintext that has been output from the decryption operation is the return value from your Java function.
I have received a message from AT5 (Atrack) unite encoded with AES-128 ECB encryption and this is the key in hex (33333838000000000000000000000000)
the original key is in string "3388"
and this is the cipher that i received but i convert it to hex
Whenever I try to decrypt the message, I face this exception:
Error while decrypting: javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher
Here is my code:
orginalString
?U??????}MgD?R???`????
#?j????g:N???#???$=???r?u?>~??Qh,?N?????3?8:?-E??;?b<J??I?v{?'o?m[?|?CY?n????K????>?ã??<?,???? ??f?'???}&?}?7r%??93??!u?0D?3Ig|??%'????*??`?Y^?M?4J?I?>?tIu???;?RR;2??{nrl??us
?R?F?oi????
String strToDecrypt = "E255898281B7C0B67D4D6744DB52FA1789F760B99B86A40A1F238B6ABCC690C1C9673A4E07EA03F79B40B2ACC8243DD098F4B10E72BA75CE3E7EE50F935168042CC74EA2F4BBE3D833F4383AE02D45C0119C3BC8623C4AD5189249FAB0BB767BA2276FB56D5BF27CE017435901DD8F6EC9DECD05B74BF51A99B1933E89C3A3AD06CA893CE72CDDEAE5F509E2D01B66A02717AADD0C917D26BA7DB1377225CCF23933E5F92175BD3044C63349677CEBC6251B27BE1FC9FD7FC32A0785F36019C2595E1EE783B64DB2344A14CE49C63EAB74174975FCE1C53BD95252113B0332CBD7A37B6E726CCFF675730DB052B14605E36F69AF11E8F3D2002D8BABEFFF508187E4C176329A3ABE08CF2B9A9F4812CF4084BACE87AD116F49C2ACD449767E758CE9184C60268AE3AAEADA052C91BF16241682E333671AC209D5BDC34CFD2B2D0C8D6D795D36A5FBD707FB56F71B3740BA86B1CEAC6E784E8E2B999CC6C9260A13F697A115C80F29C5AA38E95964731073CB051BB8A201EBAE6443A057AA69CFF41C9A593F88E2D6A712107EABCDE7042134F818268BF31896072C1B399B878BACCECC096F79A8D1835C2766EA639341E4AB22820D5AAD0F202BC896BD6C6F4D1FB1873C5BE06278D11E67F577D0120E054971088E7DB7E3A8139B20C6E22B86205BC0F4778A1DA0D6E50416FCE55DBC576A9F907FC706148204CA3C79993A4F37756427871C12EB379B4BFA0A518FFCA2BC698B1CA68AC9B3548B241C12669CEFAC9C8ECDB7B5A8149B";
secretKey = new SecretKeySpec("33333838000000000000000000000000".getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] cipherResult = cipher.doFinal(Base64.decodeBase64(strToDecrypt));
Your strToDecrypt seems to be hex encoded, not base64 encoded .. so you need to hex decode it before decrypting, instead of base64 decoding. But actually you encrypted data if hex decoded, would also end up having an invalid size. Your hex string is 1200 hex chars = 600 bytes = 37.5 AES blocks of 16 bytes .. Something seems to be wrong with your data ..
Also, your key is also Hex encoded, so you need to hex decode it .. not just do a getBytes(..).
I have done Encryption with ,
public static String encrypt(String plainText) {
try {
byte[] keyData = secret_key.getBytes();
SecretKeySpec secretKey = new SecretKeySpec(keyData, "AES/ECB/PKCS7Padding");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] cipherText = cipher.doFinal(plainText.getBytes("UTF-8"));
String encryptedString = Base64.encodeToString(cipherText, Base64.NO_WRAP);
return encryptedString;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
it's working well.
but part of Decryption gives Error like,
W/System.err: javax.crypto.BadPaddingException: pad block corrupted
W/System.err: at com.android.org.bouncycastle.jce.provider.JCEBlockCipher.engineDoFinal(JCEBlockCipher.java:701)
W/System.err: at javax.crypto.Cipher.doFinal(Cipher.java:1111)
decrypt Code like,
public static String decrypt(String encryptedText) {
try {
byte[] keyData = secret_key.getBytes();
SecretKeySpec secretKey = new SecretKeySpec(keyData, "AES/ECB/PKCS7Padding");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] cipherText = Base64.decode(encryptedText,Base64.NO_WRAP);
String decryptedString = new String(cipher.doFinal(cipherText),"UTF-8");
return decryptedString;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
here what is the problem? How can i solve this Issue?
It is likely that your secret_key value contains bytes which are not well represented in the ambiguous encoding you're using. When you call String#getBytes() without specifying an encoding, you get the system default, which can vary.
You should use hexadecimal encoding whenever you represent your key as a String. This will be consistent across serialization/deserialization on every platform. There are many standard implementations of this encoding/decoding process available (i.e. org.bouncycastle.util.encoders.Hex.decode("0123456789ABCDEFFEDCBA9876543210"); or org.apache.commons.codec.binary.Hex.decodeHex("0123456789ABCDEFFEDCBA9876543210".toCharArray()); which both return the raw byte[]).
Some side notes:
You are using ECB mode of operation, which is extremely susceptible to frequency analysis for cryptanalysis and is effectively deprecated aside from toy crypto demonstrations. I suggest you use CBC, CTR, or GCM.
You do not provide an initialization vector (IV), so the same message encrypted with the same key will always yield identical cipher text. Use a unique and non-predictable IV for every encryption operation by generating 16 bytes from SecureRandom and populating it into an IvParameterSpec. You can prepend the IV bytes to the cipher text and transport/store it in the clear.
Your cipher text is not authenticated, allowing for malicious users to both manipulate encrypted data and to attempt decryption via padding oracle/CCA attacks. Use an authenticated encryption with associated data (AEAD) mode like GCM, or use an HMAC/SHA-256 message authentication code (MAC) over the cipher text, and verify it using a constant-time equals method before attempting any decryption.
You do not need to provide the mode of operation or padding scheme when instantiating a key. SecretKey key = new SecretKeySpec(keyData, "AES"); is sufficient.
This question already has answers here:
How to decrypt a SHA-256 encrypted string?
(4 answers)
Closed 9 years ago.
I have encrypted a string using the above code.
public String encrypt(String generatedKey)
{
try {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(generatedKey.getBytes("UTF-8"));
byte digest[] = md.digest();
return (new BASE64Encoder()).encode(digest);
}
catch (Exception e) {
return null;
}
}
Similarly i need a code to decrypt the above generated code. How can i do this?
SHA is a digest algorithm, not an encryption algorithm. Digest values are not decryptable. That's why they are secure. Two different inputs may give same digest values. But it is a very little possibility. For sha256 it is 1/(2^256).
Output of digest algorithms have constant length. For SHA256 it is always 256 bit, regardless of your input length, 1 bit or 100 Gbs. If we could decrypt 256 bit digest value and have the original 1Gb input back, we would never need compression algorithms :)
Message digests produce a small "fingerprint" of a larger set of data. It's a one way procedure.
What you probably is looking for is encryption.
Key key = new SecretKeySpec(secret.getBytes(), ALGORITHM);
// Encrypt
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encryptedData = cipher.doFinal(plainText);
// Decrypt
cipher.init(Cipher.DECRYPT_MODE, key)
byte[] decryptedData = cipher.doFinal(encryptedData);
Where ALGORITHM can be one of
http://docs.oracle.com/javase/6/docs/technotes/guides/security/StandardNames.html#Cipher
I am pretty sure that we cannot decode a SHA encrypted string directly.
See this for a clear explanation: How to decrypt SHA-256 encrypted String?