Why does decryption function return garbage codes? - java

I have translate a C# based decrypt function into Java. It works fine and could be used to decrypted the passwords which have been encrypted by C# program.
Here is the source code:
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
public class TestDecrpt {
public static void main(String[] args) throws Exception {
String data = "encrypted data";
String sEncryptionKey = "encryption key";
byte[] rawData = new Base64().decode(data);
byte[] salt = new byte[8];
System.arraycopy(rawData, 0, salt, 0, salt.length);
Rfc2898DeriveBytes keyGen = new Rfc2898DeriveBytes(sEncryptionKey, salt);
byte[] IV = keyGen.getBytes(128 / 8);
byte[] keyByte = keyGen.getBytes(256 / 8);
Key key = new SecretKeySpec(keyByte, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(IV));
int pureDataLength = rawData.length - 8;
byte[] pureData = new byte[pureDataLength];
System.arraycopy(rawData, 8, pureData, 0, pureDataLength);
String plaintext = new String(cipher.doFinal(pureData), "UTF-8").replaceAll("\u0000", "");
System.out.println(plaintext);
}
}
I follow its algorithm to write the encrypt function. And codes is:
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.SecureRandom;
public class testEncrypt {
public static void main(String[] args) throws Exception {
String data = "Welcome2012~1#Welcome2012~1#Welcome2012~1#Welcome2012~1#Welcome2012~1#";
String sEncryptionKey = "encryption key"; # the same key
byte[] rawData = new Base64().decode(data);
SecureRandom random = new SecureRandom();
byte[] salt = new byte[8];
random.nextBytes(salt);
Rfc2898DeriveBytes keyGen = new Rfc2898DeriveBytes(sEncryptionKey, salt);
byte[] IV = keyGen.getBytes(128 / 8);
byte[] keyByte = keyGen.getBytes(256 / 8);
Key key = new SecretKeySpec(keyByte, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(IV));
byte[] out2 = cipher.doFinal(rawData);
byte[] out = new byte[8 + out2.length];
System.arraycopy(salt, 0, out, 0, 8);
System.arraycopy(out2, 0, out, 8, out2.length);
//String outStr=new String(out,"UTF-8");
String outStr = new Base64().encodeToString(out);
System.out.println(outStr);
System.out.print(outStr.length());
}
}
However, the encrypted data could not be decrypted correctly, it always return garbage codes, such as
ꉜ뙧巓妵峩枢펶땝ꉜ뙧巓妵峩枢펶땝ꉜ뙧巓�
Is there something wrong with the encrypt function?
================================================================================
[Update]
After changing the code to
byte[] rawData = data.getBytes("UTF-8");
The data could be encrypted and decrypted successfully.
However, the data which is encrypted in Java could not be correctly descrypted in C#.
Here is the C# version decrypt function:
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace Test
{
class Program
{
public static void Main(string[] args)
{
string data="EncryptedData";
string sEncryptionKey="EncryptionKey";
byte[] rawData = Convert.FromBase64String(data);
byte[] salt = new byte[8];
for (int i = 0; i < salt.Length; i++)
salt[i] = rawData[i];
Rfc2898DeriveBytes keyGenerator = new Rfc2898DeriveBytes(sEncryptionKey, salt);
Rijndael aes = Rijndael.Create();
aes.IV = keyGenerator.GetBytes(aes.BlockSize / 8);
aes.Key = keyGenerator.GetBytes(aes.KeySize / 8);
using (MemoryStream memoryStream = new MemoryStream())
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, aes.CreateDecryptor(), CryptoStreamMode.Write))
{
cryptoStream.Write(rawData, 8, rawData.Length - 8);
cryptoStream.Close();
byte[] decrypted = memoryStream.ToArray();
Console.Out.WriteLine(Encoding.Unicode.GetString(decrypted));
Console.In.ReadLine();
}
}
}
}
I find that the original code are using "Unicode" as output format,
Encoding.Unicode.GetString(decrypted)
so I change my Java code to "Unicode".
For Decrypt in Java:
String plaintext = new String(cipher.doFinal(pureData), "Unicode");
System.out.println(plaintext);
For Encrypt in Java:
byte[] rawData = data.getBytes("Unicode");
But using the C# code to decrypt the data which has been encrypted by the Java program still meet garbage codes.
How could I fix this issue? Is there any magical trick?
[Last Update]
After using "UTF-16LE" instead of "UTF-8", the issue has gone. It seems that "UTF-16LE" is the Java equivalent to the "Unicode" of C#.

This is the problem:
String data = "Welcome2012~1#Welcome2012~1#Welcome2012~1#Welcome2012~1#Welcome2012~1#";
byte[] rawData = new Base64().decode(data);
That text is not meant to be base64-encoded binary data. It's just text. Why are you trying to decode it as base64 data?
You want:
byte[] rawData = data.getBytes("UTF-8");
That way, when you later write:
String plaintext = new String(cipher.doFinal(pureData), "UTF-8")
.replaceAll("\u0000", "");
you're doing the reverse action. (Admittedly you probably shouldn't need the replaceAll call, but that's a different matter.)
For anything like this, you need to make sure that the steps you take on the way "out" are the reverse of the steps on the way "in". So in the correct code, you have:
Unencrypted text data => unencrypted binary data (encode via UTF-8)
Unencrypted binary data => encrypted binary data (encrypt with AES)
Encrypted binary data => encrypted text data (encode with base64)
So to reverse, we do:
Encrypted text data => encrypted binary data (decode with base64)
Encrypted binary data => unencrypted binary data (decrypt with AES)
Unencrypted binary data => unencrypted text data (decode via UTF-8)

Related

Special characters at the beginning of message after decryption

I'm encrypting a JSON message and sending it to the user. When they decrypt it, some of the messages show special characters at the beginning of the messages.
When i tried to decrypt from my side it's working fine. If they are decrypting it it shows special characters, but only for some messages as some are decrypting just fine.
Below is the Java code I am using to encrypt the messages and also adding code they are using to decrypt in .NET. Please help me understand this situation and why it's happening.
JAVA CODE(Encryption):
package com.kcs.mule.encryption;
import javax.crypto.Cipher;
import org.apache.commons.codec.binary.Base64;
import org.mule.api.MuleEventContext;
import org.mule.api.lifecycle.Callable;
import java.security.AlgorithmParameters;
import java.security.SecureRandom;
import java.util.Arrays;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
public class AESEncryption implements Callable {
private static final String password = "fvtQhQcKZVWMCXRLbqmRgfEBXYWshTEP";
private static int pswdIterations = 65536;
private static int keySize = 256;
private static byte[] ivBytes;
#Override
public Object onCall(MuleEventContext eventContext) throws Exception {
String plainText = eventContext.getMessageAsString();
byte[] saltBytes = password.getBytes("UTF-8");
// Derive the key
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), saltBytes, pswdIterations, keySize);
SecretKey secretKey = factory.generateSecret(spec);
SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");
// encrypt the message
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secret);
AlgorithmParameters params = cipher.getParameters();
ivBytes = params.getParameterSpec(IvParameterSpec.class).getIV();
byte[] encryptedTextBytes = cipher.doFinal(plainText.getBytes("UTF-8"));
byte[] encryptedOutput = new byte[ivBytes.length+encryptedTextBytes.length];
System.arraycopy(ivBytes, 0, encryptedOutput, 0, ivBytes.length);
System.arraycopy(encryptedTextBytes,0,encryptedOutput,ivBytes.length,encryptedTextBytes.length);
return encryptedOutput;
}
}
DOT Net Code(Decryption code):
byte[] saltBytes = key;
PBEKeySpec keySpec = new PBEKeySpec(key, saltBytes, 65536);
var keyHash = keySpec.GetBytes(32);
using (Aes aesCrypto = Aes.Create())
{
//set the BlockSize and the KeySize before you set the Key and the IV
//to avoid padding exceptions.
aesCrypto.BlockSize = 128;
aesCrypto.KeySize = 256; // AES256
aesCrypto.Key = keyHash;
byte[] cipherTextCombined = request.MessageBytes;
byte[] IV = new byte[aesCrypto.BlockSize / 8];
byte[] cipherText = new byte[cipherTextCombined.Length - IV.Length];
Array.Copy(cipherTextCombined, IV, IV.Length);
Array.Copy(cipherTextCombined, IV.Length, cipherText, 0, cipherText.Length);
aesCrypto.IV = IV; //Initialization vector
aesCrypto.Mode = CipherMode.CBC; //Cipher Block Chaining mode
aesCrypto.Padding = PaddingMode.PKCS7;
// Create a decryptor to perform the stream transform.
ICryptoTransform decryptor = aesCrypto.CreateDecryptor(aesCrypto.Key, aesCrypto.IV);
// Create the streams used for decryption.
using (var msDecrypt = new MemoryStream(cipherText))
{
using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (var srDecrypt = new StreamReader(csDecrypt, new UTF8Encoding(false)))
{
// Read the decrypted bytes from stream to string.
response.MessageText = srDecrypt.ReadToEnd();
}
}
}
}
}
Actual result:
����wߞ*�/�r5le": {
"System": "KCS",
"Train": {
"TrainNumber": "36181542",
"TrainID": "G-CDMY -26",
Expected Result:
TrainSchedule: {
"System": "KCS",
"Train": {
"TrainNumber": "36181542",
"TrainID": "G-CDMY -26",
It's possible You are not encrypting the string "TrainSchedule" but they are decrypting TrainSchedule along with the payload.
Either encrypt the header or tell them to separate the payload from the header before decrypting it and concatenate it after.
Or, they are only decrypting the payload and ignoring the header. Without looking at their code it's impossible to know.

Cannot decrypt AES-256 GCM with Java

I have a node module that can both encrypt and decrypt with AES-256 GCM. Now I am also trying to decrypt with Java whatever the node module encrypts, but I keep getting a AEADBadTagException.
I have tested the node module by itself and can confirm that it works as intended. I know that Java assumes the authentication tag is the last part of the message, so I ensured that the tag is the last thing appended in the node module.
Right now I'm just testing with the word, "hello". This is the encrypted message from node:
Q10blKuyyYozaRf0RVYW7bave8mT5wrJzSdURQQa3lEqEQtgYM3ss825YpCQ70A7hpq5ECPafAxdLMSIBZCxzGbv/Cj4i6W4JCJXuS107rUy0tAAQVQQA2ZhbrQ0gNV9QA==
The salt is not really being used right now because I am trying to keep things simple for testing purposes
Node module:
var crypto = require('crypto');
var encrypt = function(masterkey, plainText) {
// random initialization vector
var iv = crypto.randomBytes(12);
// random salt
var salt = crypto.randomBytes(64);
var key = masterkey;
// AES 256 GCM Mode
var cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
// encrypt the given text
var encrypted = Buffer.concat([cipher.update(plainText, 'utf8'), cipher.final()]);
// extract the auth tag
var tag = cipher.getAuthTag();
return Buffer.concat([salt, iv, encrypted, tag]).toString('base64');
};
var decrypt = function(masterkey, encryptedText) {
// base64 decoding
var bData = new Buffer(encryptedText, 'base64');
// convert data to buffers
var salt = bData.slice(0, 64);
var iv = bData.slice(64, 76);
var tag = bData.slice(bData.length - 16, bData.length);
var text = bData.slice(76, bData.length - 16);
var key = masterkey;
// AES 256 GCM Mode
var decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
decipher.setAuthTag(tag);
// encrypt the given text
var decrypted = decipher.update(text, 'binary', 'utf8') + decipher.final('utf8');
return decrypted;
};
module.exports = {
encrypt: encrypt,
decrypt: decrypt
}
Java Class:
The main method is just there for testing right now and will be removed later.
package decryption;
import java.util.Arrays;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class DecryptAES256 {
private static String salt;
private static byte[] ivBase64;
private static String base64EncryptedText;
private static String key;
public static void main(String[] args) {
String key = "123456789aabbccddeefffffffffffff";
String sourceText = "Q10blKuyyYozaRf0RVYW7bave8mT5wrJzSdURQQa3lEqEQtgYM3ss825YpCQ70A7hpq5ECPafAxdLMSIBZCxzGbv/Cj4i6W4JCJXuS107rUy0tAAQVQQA2ZhbrQ0gNV9QA==";
System.out.println(decrypt(key, sourceText));
}
public static String decrypt(String masterkey, String encryptedText) {
byte[] parts = encryptedText.getBytes();
salt = new String(Arrays.copyOfRange(parts, 0, 64));
ivBase64 = Arrays.copyOfRange(parts, 64, 76);
ivBase64 = Base64.getDecoder().decode(ivBase64);
base64EncryptedText = new String(Arrays.copyOfRange(parts, 76, parts.length));
key = masterkey;
byte[] decipheredText = decodeAES_256_CBC();
return new String(decipheredText);
}
private static byte[] decodeAES_256_CBC() {
try {
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
byte[] text = base64EncryptedText.getBytes();
GCMParameterSpec params = new GCMParameterSpec(128, ivBase64, 0, ivBase64.length);
cipher.init(Cipher.DECRYPT_MODE, skeySpec, params);
return cipher.doFinal(Base64.getDecoder().decode(text));
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Failed to decrypt");
}
}
}
The exception thrown is normal, you have 2 problems in your Java code:
1- your AES key is not decoded correctly: it is wrapped in hexadecimal representation and you decode it as if it was not. You need to convert it from the hexadecimal representation to bytes, when calling SecretKeySpec().
Replace the following line:
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
By this one:
SecretKeySpec skeySpec = new SecretKeySpec(Hex.decodeHex(key.toCharArray()), "AES");
Note that to get access to the Hex class, you need to import org.apache.commons.codec.binary.Hex in your class file and include the corresponding Apache commons-codec library in your project.
2- you split your base64 cipher text before having converted it to base64, this is not the correct order to do things:
At the start of your decrypt() method, you need to first call Base64.getDecoder().decode() on your cipher text (sourceText) before splitting it into the corresponding fields.
If you want an example of using AES-256-GCM in Java, you can look at the following example I had written some months ago: https://github.com/AlexandreFenyo/kif-idp-client
The source code to encrypt and decrypt is in the following file: https://github.com/AlexandreFenyo/kif-idp-client/blob/master/src/kif/libfc/Tools.java
See the methods named encodeGCM() and decodeGCM().
Those methods are called by the main class here: https://github.com/AlexandreFenyo/kif-idp-client/blob/master/src/kif/libfc/CommandLine.java

3DES (DESede)- Decrypt encrypted text (done by JAVA) in C#

The encrypted text is done in JAVA (which we have no JAVA background at all)
The decryption will be in C#, and here is the code
public static string DecryptString(string Message, string Passphrase)
{
byte[] Results;
UTF8Encoding UTF8 = new UTF8Encoding();
MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));
// byte[] TDESKey = UTF8.GetBytes(Passphrase);
TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();
TDESAlgorithm.Key = TDESKey;
// TDESAlgorithm.Mode = CipherMode.CTS;
TDESAlgorithm.Padding = PaddingMode.Zeros;
byte[] DataToDecrypt = Convert.FromBase64String(Message);
try
{
ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor();
Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length);
}
finally
{
TDESAlgorithm.Clear();
HashProvider.Clear();
}
return Encoding.UTF8.GetString(Results);
}
Encrypted Java code is
public String encryptData(String privateKey, String rawData)
{
Cipher cipher = null;
try
{
cipher = Cipher.getInstance(DESEDE_ENCRYPTION_SCHEME);
cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(privateKey));
byte[] plainText = rawData.getBytes(UNICODE_FORMAT);
byte[] encryptedText = cipher.doFinal(plainText);
return new String(Base64.encodeBase64(encryptedText));
}
}
However, when tried to decrypt, got the error message: BAD DATA
Where am I missing here?
You are not using MD5 in Java, so you should not be using it in your .NET for computing the hash.
Your key should have been generated using a specific encoding and same you should use in .NET.
Please note, there is some fundamental difference in java KeySpec and the Key being used for TripleDESCryptoServiceProvider. As mentioned by Microsfot https://msdn.microsoft.com/en-us/library/system.security.cryptography.tripledescryptoserviceprovider.aspx
Triple DES only supports "key lengths from 128 bits to 192 bits in increments of 64 bits"
So you need to convert your key appropriately before assigning. To do this you can use the Array.Resize method as following.
byte[] TDESKey = Encoding.UTF8.GetBytes(Passphrase);
System.Array.Resize(ref TDESKey , 192 / 8);
Hope this will help.

Encrypt in Ruby and Decrypt in Java - Why is it not working?

What am I doing wrong? I expected the Java program to print "private". My goal is to try to write the MessageEncryptor.decrypt ruby method in Java.
Ruby encryption (most code was taken from MessageEncryptor, but modified not to Marshal), but I've extracted it so that it's easier to see what's going on:
require 'openssl'
require 'active_support/base64'
#cipher = 'aes-256-cbc'
d = OpenSSL::Cipher.new(#cipher)
#secret = OpenSSL::PKCS5.pbkdf2_hmac_sha1("password", "some salt", 1024, d.key_len)
cipher = OpenSSL::Cipher::Cipher.new(#cipher)
iv = cipher.random_iv
cipher.encrypt
cipher.key = #secret
cipher.iv = iv
encrypted_data = cipher.update("private")
encrypted_data << cipher.final
puts [encrypted_data, iv].map {|v| ::Base64.strict_encode64(v)}.join("--")
Which printed:
tzFUIVllG2FcYD7xqGPmHQ==--UAPvdm3oN3Hog9ND9HrhEA==
Java code:
package decryptruby;
import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
public class DecryptRuby {
public static String decrypt(String encrypted, String pwd, byte[] salt)
throws Exception {
String[] parts = encrypted.split("--");
if (parts.length != 2) return null;
byte[] encryptedData = Base64.decodeBase64(parts[0]);
byte[] iv = Base64.decodeBase64(parts[1]);
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec spec = new PBEKeySpec(pwd.toCharArray(), salt, 1024, 256);
SecretKey tmp = factory.generateSecret(spec);
SecretKey aesKey = new SecretKeySpec(tmp.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, aesKey, new IvParameterSpec(iv));
byte[] result = cipher.doFinal(encryptedData);
return result.toString();
}
public static void main(String[] args) throws Exception {
String encrypted = "tzFUIVllG2FcYD7xqGPmHQ==--UAPvdm3oN3Hog9ND9HrhEA==";
System.out.println("Decrypted: " + decrypt(encrypted, "password", "some salt".getBytes()));
}
}
Which printed
Decrypted: [B#432a0f6c
This is the problem - or at least a problem:
byte[] result = cipher.doFinal(encryptedData);
return result.toString();
You're calling toString() on a byte array. Arrays don't override toString(). That won't give you what you want at all - as you can see. Instead, you need to write something like:
return new String(result, "UTF-8");
... but you need to know what encoding was used to turn the original string into bytes before encryption. It's not clear to me from the Ruby code what encoding is used, but if you can be explicit about it (ideally using UTF-8) it'll make your life a lot easier.
In short, I suspect this problem has nothing to do with encryption at all - it has everything to do with converting text to bytes in Ruby and then converting the same sequence of bytes back into a string in Java.
Of course the encryption may be failing as well but that's a different matter.

Java AES CBC Decryption

PHP Encrypt Function
$privateKey = "1234567812345678";
$iv = "1234567812345678";
$data = "Test string";
$encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $privateKey, $data, MCRYPT_MODE_CBC, $iv);
echo(base64_encode($encrypted));
Result: iz1qFlQJfs6Ycp+gcc2z4w==
When I try to decrypt this result in Java using the function below, all I get back is ì�š#ÔBKxnfÈ~¯Ô'M while I am expecting "Test string". Any ideas where I am wrong? Thanks
public static String decrypt() throws Exception{
try{
String Base64EncodedText = "iz1qFlQJfs6Ycp+gcc2z4w==";
String decodedText = com.sun.xml.internal.messaging.saaj.util.Base64.base64Decode(Base64EncodedText);
String key = "1234567812345678";
String iv = "1234567812345678";
javax.crypto.spec.SecretKeySpec keyspec = new javax.crypto.spec.SecretKeySpec(key.getBytes(), "AES");
javax.crypto.spec.IvParameterSpec ivspec = new javax.crypto.spec.IvParameterSpec(iv.getBytes());
javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance("AES/CBC/NoPadding");
cipher.init(javax.crypto.Cipher.DECRYPT_MODE, keyspec, ivspec);
byte[] decrypted = cipher.doFinal(decodedText.getBytes());
String str = new String(decrypted);
return str;
}catch(Exception e){
return null;
}
}
EDIT: As of Java 8 Java now includes an acceptable Base64 class, java.util.Base64.
This line
String decodedText = com.sun.xml.internal.messaging.saaj.util.Base64.base64Decode(Base64EncodedText);
looks wrong. Instead, use the apache commons codec classes or the Harder base64 class. Also the default padding used by mcrypt, zero padding, is arguably wrong and makes it difficult to use the results in other languages. The users comments section for the mcrypt_encrypt web pages has examples of how to do this.
Here is small example that uses the apache commons classes to decrypt your string.
import java.nio.charset.Charset;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
public class AESToy3 {
private static final Charset ASCII = Charset.forName("US-ASCII");
public static void main(String[] args) throws Exception {
String base64Cipher = "iz1qFlQJfs6Ycp+gcc2z4w==";
byte [] cipherBytes = Base64.decodeBase64(base64Cipher);
byte [] iv = "1234567812345678".getBytes(ASCII);
byte [] keyBytes = "1234567812345678".getBytes(ASCII);
SecretKey aesKey = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/NOPADDING");
cipher.init(Cipher.DECRYPT_MODE, aesKey, new IvParameterSpec(iv));
byte[] result = cipher.doFinal(cipherBytes);
System.out.println(Hex.encodeHexString(result));
}
}
this produces the following output:
5465737420737472696e670000000000
which when decoded as ASCII and removing the trailing zeros gives you Test string

Categories

Resources