I am trying to encode byte[] to String, then decode this String to byte[], my code is:
byte[] aaa = new byte[1];
aaa[0] = (byte) 153;
String encoder = Base64.encodeBase64String(aaa);
System.out.println("encoder <<>> " + encoder);
// Decode the Base64 String.
byte[] bytes = Base64.decodeBase64(encoder);
String decoder = new String(bytes, "UTF08");
System.out.println("decoder <<>> " + decoder );
Result is:
encoder <<>> mQ==
decoder <<>> ?
The result are not the same one. Why does this happen?
Try this:
byte[] aaa = new byte[1];
aaa[0] = (byte) 153;
System.out.println("original bytes <<>> " + Arrays.toString(aaa));
// Encode the bytes to Base64
String encoder = Base64.encodeBase64String(aaa);
System.out.println("encoder <<>> " + encoder);
// Decode the Base64 String to bytes
byte[] bytes = Base64.decodeBase64(encoder);
System.out.println("decoded bytes <<>> " + Arrays.toString(bytes));
simple static utility methods to encode and decode the given string.
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
...
private static byte[] key = {
0x74, 0x68, 0x69, 0x73, 0x49, 0x73, 0x41, 0x53, 0x65, 0x63, 0x72, 0x65, 0x74, 0x4b, 0x65, 0x79
}; // "ThisIsASecretKey";
public static String encrypt(String stringToEncrypt) throws Exception {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
final SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
final String encryptedString = Base64.encodeBase64String(cipher.doFinal(stringToEncrypt.getBytes()));
return encryptedString;
}
public static String decrypt(String stringToDecrypt) throws Exception {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
final SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
final String decryptedString = new String(cipher.doFinal(Base64.decodeBase64(stringToDecrypt)));
return decryptedString;
}
Related
I have the following Decryption code from a C# App written by a colleague:
private static string UrlEncryptionKey = "x0iiR!RG#753!"; // not real values here
private static byte[] salt = new byte[] { 0x41, 0x71, 0x61, 0x6e, 0x21, 0x4d, 0x65, 0x64, 0x76, 0x64, 0x63, 0x62, 0x72 }
public static string Decrypt(String cipherText)
{
byte[] cipherBytes = Convert.FromBase64String(cipherText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(UrlEncryptionKey, salt);
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(cipherBytes, 0, cipherBytes.Length);
cs.Close();
}
cipherText = Encoding.Unicode.GetString(ms.ToArray());
}
}
return cipherText;
}
Piecing together the equivalent cryptography, I currently have the Java equivalent as:
public static String Decrypt(String cipherText) throws Exception {
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
PBEKeySpec pbeKeySpec = new PBEKeySpec(UrlEncryptionKey.toCharArray(), salt, 1000, 384);
Key secretKey = factory.generateSecret(pbeKeySpec);
byte[] key = new byte[32];
byte[] iv = new byte[16];
System.arraycopy(secretKey.getEncoded(), 0, key, 0, 32);
System.arraycopy(secretKey.getEncoded(), 32, iv, 0, 16);
AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv);
SecretKey secretKeyAES = new SecretKeySpec(secretKey.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKeyAES, ivSpec);
byte[] decoded = Base64.getDecoder().decode(cipherText.getBytes("UTF-8"));
byte[] original = cipher.doFinal(decoded);
String originalString = new String(original, "UTF-8");
return originalString;
}
But it's throwing an exception:
Exception in thread "main" java.security.InvalidKeyException: Invalid AES key length: 48 bytes
at com.sun.crypto.provider.AESCrypt.init(AESCrypt.java:87)
at com.sun.crypto.provider.CipherBlockChaining.init(CipherBlockChaining.java:93)
at com.sun.crypto.provider.CipherCore.init(CipherCore.java:591)
at com.sun.crypto.provider.AESCipher.engineInit(AESCipher.java:346)
at javax.crypto.Cipher.implInit(Cipher.java:809)
at javax.crypto.Cipher.chooseProvider(Cipher.java:867)
at javax.crypto.Cipher.init(Cipher.java:1399)
at javax.crypto.Cipher.init(Cipher.java:1330)
at scratch.AESUtil.Decrypt(AESUtil.java:55)
at scratch.AESUtil.main(AESUtil.java:93)
I don't understand why the key length is invalid
I am using a C# "encrypt" and need a Java "decrypt" method. I need help in java that i can't replicate C# decryption on java and it is not explicit Padding on C# , i don't know what use in java and my key size I think is different but I am not sure. I'm very confused.
know that i need change Java Policy , and did it ! and Change Key size JAVA to 32 bytes.
C#
using System;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using Voa.Cross.Util.Extensions;
namespace Voa.Core.Safeties
{
public class Security
{
private readonly string _defaultKey = "sjkdhfjksdhf3444KDFK4nFLFGKdsnjcnj2cmkeKDIK484dmd999sksksksUUddUZ83k030394m49jdjPuWzRk8Zq2PfnpR3YrYWSq2AaUT6meeC3tr36nTVkuudKWbDyPjhUwbwXBzkUhSPKPpSRheR49em4qJWa6YHSCjKX3K93FEMnqXhYauXwjJwbHXfPWTSdxy6ebCBPyAfqk7Uz5nrRddVjZrxWNCMZYG3PbcvPWA34ekdkd454ldnvJKl";
private readonly int _divisionKey = 4;
private readonly byte[] _iv = new byte[16] {0x26, 0xdc, 0xff, 0x00, 0xad, 0xed, 0x7a, 0xee, 0xc5, 0xfe, 0x07, 0xaf, 0x4d, 0x08, 0x22, 0x3c};
private byte[] _key;
public Security() => _key = SHA256.Create().ComputeHash(Encoding.ASCII.GetBytes(_defaultKey));
public string Encrypt(string data, string key)
{
if (!string.IsNullOrEmpty(key))
{
CustomKey(key);
}
var encryptor = Aes.Create();
encryptor.Mode = CipherMode.CBC;
// Set key and IV
var aesKey = new byte[32];
Array.Copy(_key, 0, aesKey, 0, 32);
encryptor.Key = aesKey;
encryptor.IV = _iv;
var memoryStream = new MemoryStream();
var aesEncryptor = encryptor.CreateEncryptor();
var cryptoStream = new CryptoStream(memoryStream, aesEncryptor, CryptoStreamMode.Write);
var plainBytes = Encoding.ASCII.GetBytes(data);
cryptoStream.Write(plainBytes, 0, plainBytes.Length);
cryptoStream.FlushFinalBlock();
var cipherBytes = memoryStream.ToArray();
memoryStream.Close();
cryptoStream.Close();
var cipherText = Convert.ToBase64String(cipherBytes, 0, cipherBytes.Length);
return cipherText;
}
public string Decrypt(string data, string key)
{
if (!string.IsNullOrEmpty(key))
{
CustomKey(key);
}
var encryptor = Aes.Create();
encryptor.Mode = CipherMode.CBC;
var aesKey = new byte[32];
Array.Copy(_key, 0, aesKey, 0, 32);
encryptor.Key = aesKey;
encryptor.IV = _iv;
var memoryStream = new MemoryStream();
var aesDecryptor = encryptor.CreateDecryptor();
var cryptoStream = new CryptoStream(memoryStream, aesDecryptor, CryptoStreamMode.Write);
var plainText = string.Empty;
try
{
var cipherBytes = Convert.FromBase64String(data);
cryptoStream.Write(cipherBytes, 0, cipherBytes.Length);
cryptoStream.FlushFinalBlock();
var plainBytes = memoryStream.ToArray();
plainText = Encoding.ASCII.GetString(plainBytes, 0, plainBytes.Length);
}
finally
{
memoryStream.Close();
cryptoStream.Close();
}
return plainText;
}
private void CustomKey(string key)
{
var blockSize = key.Length / _divisionKey;
var splitKey = key.CutString(blockSize).ToList();
var splitDefaultKey = _defaultKey.CutString(blockSize).ToList();
var newKey = string.Concat(splitDefaultKey.Intertwine(splitKey).ToList());
_key = SHA256.Create().ComputeHash(Encoding.ASCII.GetBytes(newKey));
}
}
}
JAVA test...
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class SecurityAESEncryption {
private static final String _key = "sjkdhfjksdhf3444KDFK4nFLFGKdsnjcnj2cmkeKDIK484dmd999sksksksUUddUZ83k030394m49jdjPuWzRk8Zq2PfnpR3YrYWSq2AaUT6meeC3tr36nTVkuudKWbDyPjhUwbwXBzkUhSPKPpSRheR49em4qJWa6YHSCjKX3K93FEMnqXhYauXwjJwbHXfPWTSdxy6ebCBPyAfqk7Uz5nrRddVjZrxWNCMZYG3PbcvPWA34ekdkd454ldnvJKl";
private static final char[] initCharArray = new char[] {0x26, 0xdc, 0xff, 0x00, 0xad, 0xed, 0x7a, 0xee, 0xc5, 0xfe, 0x07, 0xaf, 0x4d, 0x08, 0x22, 0x3c};
private static final byte[] initVector = SecurityAESEncryption.charToByteArray(initCharArray);
//private static final String initArray = "26dcff00aded7aeec5fe07af4d08223c";
//private static final byte[] ivValue = SecurityAESEncryption.hexStringToByteArray(initArray);
//private static final byte[] key = DigestUtils.sha256(_key.getBytes(StandardCharsets.US_ASCII)).;
private static final byte[] key = SecurityAESEncryption.computeHash(_key);
public static String encrypt(String value) {
try {
System.out.println(key.length);
System.out.println(Base64.decodeBase64(key).length);
byte[] aesKey = new byte[32];
System.arraycopy(key, 0, aesKey, 0, 32);
SecretKeySpec skeySpec = new SecretKeySpec(aesKey, "AES");
IvParameterSpec iv = new IvParameterSpec(initVector);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(value.getBytes());
return Base64.encodeBase64String(encrypted);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static String decrypt(String encrypted) {
try {
byte[] encryptedBytes = Base64.decodeBase64(encrypted);
System.out.println(key.length);
System.out.println(Base64.decodeBase64(key).length);
byte[] aesKey = new byte[32];
System.arraycopy(key, 0, aesKey, 0, 32);
IvParameterSpec iv = new IvParameterSpec(initVector);
SecretKeySpec skeySpec = new SecretKeySpec(aesKey, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
//byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted));
byte[] original = cipher.doFinal(encryptedBytes);
return new String(original,StandardCharsets.US_ASCII);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static byte[] charToByteArray(char[] x)
{
final byte[] res = new byte[x.length];
for (int i = 0; i < x.length; i++)
{
res[i] = (byte) x[i];
}
return res;
}
public static byte[] computeHash(String input) {
try {
// Static getInstance method is called with hashing SHA
MessageDigest md = MessageDigest.getInstance("SHA-256");
return md.digest(input.getBytes(StandardCharsets.US_ASCII));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
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;
}
public static void main(String[] args) {
String originalString = "123456!##";
System.out.println("Original String to encrypt - " + originalString);
String encryptedString = encrypt(originalString);
System.out.println("Encrypted String - " + encryptedString);
String decryptedString = decrypt("Ci10C7ZjUPoEnitdh7QkEw==");
System.out.println("After decryption - " + decryptedString);
}
Your edited Java prog now successfully encrypts the string "123456!##" to this (Base64 encoded) string "LnZV0Vph+eUeJLT2Gst0kw==" using a String as input to a SHA-256 digest, so the real key used for en-/decryption is
(hex) "07c3491eaa6a6289ca91b7b0f290d60688538860b44753f1cf9617977985d2db".
Using this encoded string as input for your decrypt method returns the original string but when using the encoded/encrypted
string "Ci10C7ZjUPoEnitdh7QkEw==" I'm running into this exception:
javax.crypto.BadPaddingException: Given final block not properly padded.
Such issues can arise if a bad key is used during decryption.
Imho this indicates that the key your're using on Java-side is not the same as on C#-side (we don't see the real input
to Encrypt and I don't know what "CustomKey" is doing :-).
Could you please print out
the aeskey and -iv from your C#-Encrypt method directly after you setup them in encryptor-inits and share them here,
that might be usefull for us to help.
public string Encrypt(string data, string key)
...
// Set key and IV
var aesKey = new byte[32];
Array.Copy(_key, 0, aesKey, 0, 32);
encryptor.Key = aesKey;
encryptor.IV = _iv;
==> print aesKey & _iv
...
Help me on Java equivalent of PHP AES Encryption.
I tried with java AES encryption it was working but the below equivalent php code not giving correct encryption decryption with java
I have given php and equivalent java code, but result is not expected one.
PHP code:
function encrypt($plainText)
{
$key='12345678912345671234567891234567'; //size 32
$md5=md5($key);
$plainText='I am plain text';
$secretKey = hextobin($md5);
$initVector = pack("C*", 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f);
$openMode = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '','cbc', '');
$blockSize = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, 'cbc');
$plainPad = pkcs5_pad($plainText, $blockSize);
if (mcrypt_generic_init($openMode, $secretKey, $initVector) != -1)
{
$encryptedText = mcrypt_generic($openMode, $plainPad);
mcrypt_generic_deinit($openMode);
}
$data = bin2hex($encryptedText);
return $data;
}
function decrypt($encryptedText)
{
$key='12345678912345671234567891234567';
$md5=md5($key);
$secretKey = hextobin($md5);
$initVector = pack("C*", 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f);
$encryptedText=hextobin($encryptedText);
$openMode = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '','cbc', '');
mcrypt_generic_init($openMode, $secretKey, $initVector);
$decryptedText = mdecrypt_generic($openMode, $encryptedText);
$decryptedText = rtrim($decryptedText, "\0");
mcrypt_generic_deinit($openMode);
return $decryptedText;
}
//*********** Padding Function *********************
function pkcs5_pad ($plainText, $blockSize)
{
$pad = $blockSize - (strlen($plainText) % $blockSize);
return $plainText . str_repeat(chr($pad), $pad);
}
//********** Hexadecimal to Binary function for php 4.0 version ********
function hextobin($hexString)
{
$length = strlen($hexString);
$binString="";
$count=0;
while($count<$length)
{
$subString =substr($hexString,$count,2);
$packedString = pack("H*",$subString);
if ($count==0)
{
$binString=$packedString;
}
else
{
$binString.=$packedString;
}
$count+=2;
}
return $binString;
}
Java code:
public class StatusAES2 {
private static final String key = "12345678912345671234567891234567";
public static void main(String[] args) {
String plainText = "I am plain text";
System.out.println("Original String to encrypt - " + plainText);
String encryptedString = encrypt(plainText);
System.out.println("Encrypted String - " + encryptedString);
String decryptedString = decrypt(encryptedString);
System.out.println("After decryption - " + decryptedString);
}
public static String encrypt(String value) {
try {
byte[] keybytes=key.getBytes("UTF-8");
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] thedigest = md.digest(keybytes);
String md5Str=Hex.encodeHexString(thedigest);
IvParameterSpec iv = new IvParameterSpec(new byte[]{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15});
keybytes=hextobin(md5Str).getBytes();
SecretKeySpec skeySpec = new SecretKeySpec(keybytes, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(value.getBytes());
String encryptedText=Hex.encodeHexString(encrypted);//bin2hex
return encryptedText;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static String decrypt(String encrypted) {
try {
byte[] keybytes=key.getBytes("UTF-8");
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] thedigest = md.digest(keybytes);
String md5Str=Hex.encodeHexString(thedigest);
IvParameterSpec iv = new IvParameterSpec(new byte[]{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15});
keybytes=hextobin(md5Str).getBytes();
SecretKeySpec skeySpec = new SecretKeySpec(keybytes, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] original = cipher.doFinal(Hex.decodeHex(encrypted.toCharArray()));
return new String(original);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static String hextobin(String s) throws DecoderException, UnsupportedEncodingException {
int length=s.length();
int count=0;
String binString="";
while(count<length){
int c=count+2;
String subs=s.substring(count,c);
String packedString="";
byte[] somevar = DatatypeConverter.parseHexBinary(subs);
byte[] bytes = Hex.decodeHex(subs.toCharArray());
packedString=new String(bytes, "UTF-8");
if (count==0){
binString=packedString;
}else {
binString=binString+packedString;
}
count=count+2;
}
return binString;
}
}
Add this dependency.
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk16</artifactId>
<version>1.46</version>
</dependency>
Try this
CBCBlockCipher cbcBlockCipher = new CBCBlockCipher(new AESEngine());
SecureRandom random = new SecureRandom();
KeyParameter key = new KeyParameter(yourSecretKey);
BlockCipherPadding blockCipherPadding = new PKCS7Padding();
PaddedBufferedBlockCipher pbbc = new PaddedBufferedBlockCipher(cbcBlockCipher, blockCipherPadding);
private byte[] processing(byte[] input, boolean encrypt) throws DataLengthException, InvalidCipherTextException {
int blockSize = cbcBlockCipher.getBlockSize();
int inputOffset = 0;
int inputLength = input.length;
int outputOffset = 0;
byte[] initializationVector = new byte[blockSize];
if (encrypt) {
random.nextBytes(initializationVector);
outputOffset += blockSize;
} else {
System.arraycopy(input, 0, initializationVector, 0, blockSize);
inputOffset += blockSize;
inputLength -= blockSize;
}
pbbc.init(encrypt, new ParametersWithIV(key, initializationVector));
byte[] output = new byte[pbbc.getOutputSize(inputLength) + outputOffset];
if (encrypt) {
System.arraycopy(initializationVector, 0, output, 0, blockSize);
}
int outputLength = outputOffset + pbbc.processBytes(input, inputOffset, inputLength, output, outputOffset);
outputLength += pbbc.doFinal(output, outputLength);
return Arrays.copyOf(output, outputLength);
}
I'm using Triple DES for my encryption/decryption purpose but somehow it gives me above exception and I tried other approaches as well mentioned in the related answers, but I'm stuck. I'm new to cryptography and corresponding java libs.
private static byte[] Key = new byte[] {
0x42, 0x45, 0x49, 0x30, 0x12, 0x22, 0x35, 0x48, 0x33, 0x24, 0x28, 0x51,
0x48, 0x24, 0x30, 0x21, 0x44, 0x31, 0x14, 0x19, 0x45, 0x34, 0x47, 0x25 };
Cipher c;
public EncryptionHelper() throws Exception {
// byte[] key_hash = (Key).toString().getBytes("UTF-8");
// key_hash = Arrays.copyOf(key_hash, 32);
SecretKey key = new SecretKeySpec(Key, 0, Key.length, "DESede");
c = Cipher.getInstance("DESede/ECB/PKCS5Padding");
c.init(Cipher.ENCRYPT_MODE, key);
}
public String Encrypt(String S) throws Exception {
byte[] base64EncryptedText = S.getBytes("UTF-8");
byte EncryptedText[] = c.doFinal(base64EncryptedText, 0, base64EncryptedText.length);
return new String(EncryptedText);
}
public String Decrypt(String S) throws Exception {
Cipher c2 = null;
// byte[] key_hash = (Key).toString().getBytes("UTF-8");
// key_hash = Arrays.copyOf(key_hash, 24);
SecretKey key = new SecretKeySpec(Key,0, Key.length, "DESede");
c2 = Cipher.getInstance("DESede/ECB/PKCS5Padding");
c2.init(Cipher.DECRYPT_MODE, key);
byte[] base64EncryptedText = Base64.getEncoder().encode(S.getBytes());
byte[] textDecrypted = c2.doFinal(base64EncryptedText, 0, base64EncryptedText.length);
return new String(textDecrypted, "UTF-8");
}
EDIT:
Finally worked through the solution, I was just misplacing the components, specified the core logic as well.
public class EncryptionHelper {
private static byte[] Key = new byte[] {
0x42, 0x45, 0x49, 0x30, 0x12, 0x22, 0x35, 0x48, 0x33, 0x24, 0x28, 0x51,
0x48, 0x24, 0x30, 0x21, 0x44, 0x31, 0x14, 0x19, 0x45, 0x34, 0x47, 0x25 };
static Cipher c;
public EncryptionHelper() throws Exception {
// byte[] key_hash = (Key).toString().getBytes("UTF-8");
// key_hash = Arrays.copyOf(key_hash, 32);
SecretKey key = new SecretKeySpec(Key, 0, Key.length, "DESede");
c = Cipher.getInstance("DESede/ECB/PKCS5Padding");
c.init(Cipher.ENCRYPT_MODE, key);
}
public static String Encrypt(String S) throws Exception {
byte[] base64EncryptedText = S.getBytes("UTF-8");
byte EncryptedText[] = c.doFinal(base64EncryptedText, 0, base64EncryptedText.length);
return new String(Base64.getEncoder().encode(EncryptedText));
}
// LOGIC:
// for encryption: string -> utf-8 byte array,
// encrypt and return a base 64 encoded string
// for decryption: String -> base64 -> decode base 64 array,
// decrypt and return utf-8 string
public static String Decrypt(String S) throws Exception {
Cipher c2 = null;
// byte[] key_hash = (Key).toString().getBytes("UTF-8");
// key_hash = Arrays.copyOf(key_hash, 24);
SecretKey key = new SecretKeySpec(Key, "DESede");
c2 = Cipher.getInstance("DESede/ECB/PKCS5Padding");
c2.init(Cipher.DECRYPT_MODE, key);
byte[] base64EncryptedText = Base64.getDecoder().decode(S.getBytes());
byte[] textDecrypted = c2.doFinal(base64EncryptedText, 0, base64EncryptedText.length);
return new String(textDecrypted, "UTF-8");
}
Despite the names on your variables you have failed to base64-encode the result of encryption in your Encrypt method. Therefore, when you convert it to String you get garbage, and when you base64 decode that garbage in your Decrypt method you get garbage2.
You are base64-decoding and then decrypting, but you are not encrypting and then base64-encoding.
Our library used import com.sun.org.apache.xml.internal.security.utils.Base64;
and it seems we are encouraged to use something else
import org.apache.commons.codec.binary.Base64;
(Package com.sun.org.apache.xml.internal.security.utils.Base64 does not exist)
Thing is you have to change your encrypt/decrypt code as well, and I'm not sure how I should change them.
As of now, I get Input length must be multiple of 16 when decrypting with padded cipher error
(Encrypt and decrypt with AES and Base64 encoding)
Anyone care to show the right way to do this? or I strongly suspect there should be a git repo that does this but couldn't find it..
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
#Service
public class SecureModule {
private Logger log = LoggerFactory.getLogger(getClass());
public static byte[] ivBytes = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
public static final String Decrypt(String text, String key) throws Exception
{
byte[] textBytes = Base64.decodeBase64(text);
//byte[] textBytes = str.getBytes("UTF-8");
AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
SecretKeySpec newKey = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, newKey, ivSpec);
return new String(cipher.doFinal(textBytes), "UTF-8");
}
public static final String DecryptAndBase64(String text, String key) throws Exception
{
byte[] textBytes = Base64.decodeBase64(text);
//byte[] textBytes = str.getBytes("UTF-8");
AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
SecretKeySpec newKey = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, newKey, ivSpec);
String Result="";
// tried but doens't work
// Result = new String(cipher.doFinal(new Base64().decode(text.getBytes())), "UTF-8");
Result = new String(Base64.decodeBase64(new String(cipher.doFinal(textBytes), "UTF-8").getBytes()));
return Result;
= }
public static final String Encrypt(String text, String key) throws Exception
{
byte[] textBytes = text.getBytes("UTF-8");
AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
SecretKeySpec newKey = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
Cipher cipher = null;
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
// cipher = Cipher.getInstance("AES/CBC");
cipher.init(Cipher.ENCRYPT_MODE, newKey, ivSpec);
byte[] sResult = cipher.doFinal(textBytes);
String ssResult = Base64.encodeBase64String(sResult);
return ssResult;
}
public static final String EncryptAndBase64(String text, String key) throws Exception
{
String plaintext = "";
plaintext = new String(Base64.encodeBase64(text.getBytes()));
byte[] textBytes = plaintext.getBytes("UTF-8");
AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
SecretKeySpec newKey = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
Cipher cipher = null;
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, newKey, ivSpec);
return Base64.encodeBase64String(cipher.doFinal(textBytes));
}
}