Java javax.crypto.AEADBadTagException: Tag mismatch - java

Can someone help on why I am getting "javax.crypto.AEADBadTagException: Tag mismatch" error? Not sure, what I am missing.
Below is the decryption util code. EncryptedData includes initVector as well.
import org.apache.commons.codec.binary.Base64
import javax.crypto.Cipher
import javax.crypto.SecretKey
import javax.crypto.spec.GCMParameterSpec
import javax.crypto.spec.SecretKeySpec
import java.nio.ByteBuffer
import java.nio.charset.Charset
import java.nio.charset.StandardCharsets
import java.security.SecureRandom
class GCMEncryptionUtil {
static final String AES = "AES"
static final String AES_GCM_NO_PADDING = "AES/GCM/NoPadding"
static final int TAG_LENGTH_BIT = 128
static final int IV_LENGTH_BYTE = 12
private static final Charset UTF_8 = StandardCharsets.UTF_8
public static void main(String[] args) {
String encryptedDataWithIV = args[0]
SecretKey key = generateSecretFromSymmetricKey("thisismysecretkey")
decrypt(encryptedDataWithIV, key)
}
static String decrypt(String encryptedData, SecretKey secret) throws Exception {
byte[] encryptedDataInBytes = Base64.decodeBase64(encryptedData)
ByteBuffer cipherTextBuffer = ByteBuffer.wrap(encryptedDataInBytes)
// Get IV from cipherText
byte[] iv = new byte[IV_LENGTH_BYTE]
cipherTextBuffer.get(iv)
// Remove IV from cipherText which is actual payload to be decrypted
byte[] cipherText = new byte[cipherTextBuffer.remaining()]
cipherTextBuffer.get(cipherText)
Cipher cipher = Cipher.getInstance(AES_GCM_NO_PADDING)
cipher.init(Cipher.DECRYPT_MODE, secret, new GCMParameterSpec(TAG_LENGTH_BIT, iv))
byte[] plainText = cipher.doFinal(cipherText)
return new String(plainText, UTF_8)
}
static SecretKey generateSecretFromSymmetricKey(String key) {
byte[] bytes = Base64.decodeBase64(key)
new SecretKeySpec(bytes, 0, bytes.length, AES)
}
}

Related

BadPaddingException during AES decryption for long length string

public class AESEncryptionDecryption {
public static void main(String[] args) throws Exception {
String message = "FUN dfdf fgfgf dfffgf";
String randomNo = generateRandom(16); //16digit random number is generated.
//ENCRYPTION
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
//byte[] ivBytes = Arrays.copyOfRange(randomNo.getBytes("UTF-8"), 0, 16);
IvParameterSpec iv = new IvParameterSpec(randomNo.getBytes("UTF-8"));
SecretKeySpec keyspec = new SecretKeySpec(randomNo.getBytes("UTF-8"), "AES");
cipher.init(Cipher.ENCRYPT_MODE, keyspec, iv);
cipher.update(message.getBytes("UTF-8"));
byte[] cipherText = cipher.doFinal();
//DECRYPTION
byte[] data = Base64.decodeBase64(base64);
cipher.init(Cipher.DECRYPT_MODE, keyspec, iv);
cipher.update(cipherText);
byte[] decryptedMessage = cipher.doFinal();
System.out.println("Decrypted Message :: " + new String(decryptedMessage,"UTF-8"));
}
}
I am receiving the exception only for the strings of longer length, for smaller length strings its working fine.
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class PasswordEncrypt {
public static String ALGORITHM = "AES";
private static String AES_CBS_PADDING = "AES/CBC/PKCS5Padding";
private static int AES_128 = 128;
private static byte[] encryptDecrypt(final int mode, final byte[] key, final byte[] IV, final byte[] message)
throws Exception {
final Cipher cipher = Cipher.getInstance(AES_CBS_PADDING);
final SecretKeySpec keySpec = new SecretKeySpec(key, ALGORITHM);
final IvParameterSpec ivSpec = new IvParameterSpec(IV);
cipher.init(mode, keySpec, ivSpec);
return cipher.doFinal(message);
}
public static Map<String, SecretKey> keyGenerator() throws NoSuchAlgorithmException{
Map<String, SecretKey> map = new HashMap<String, SecretKey>();
KeyGenerator keyGenerator = KeyGenerator.getInstance(PasswordEncrypt.ALGORITHM);
keyGenerator.init(AES_128);
SecretKey key = keyGenerator.generateKey();
map.put("key", key);
SecretKey IV = keyGenerator.generateKey();
map.put("iv", IV);
return map;
}
public static String encrypt(String message) throws Exception{
Map<String , SecretKey> map = keyGenerator();
SecretKey key = map.get("key");
SecretKey IV = map.get("iv");
byte[] cipherText = encryptDecrypt(Cipher.ENCRYPT_MODE, key.getEncoded(), IV.getEncoded(), message.getBytes());
String encrypted_message = Base64.getEncoder().encodeToString(cipherText);
String encodedKey = Base64.getEncoder().encodeToString(map.get("key").getEncoded());
String encodedIV = Base64.getEncoder().encodeToString(map.get("iv").getEncoded());
return encrypted_message+"javax"+encodedIV+"javax"+encodedKey;
}
public static String decrypt(String encryptedMessage) throws Exception{
String[] result = encryptedMessage.split("javax");
byte[] decodedIV = Base64.getDecoder().decode(result[1]);
byte[] decodedKey = Base64.getDecoder().decode(result[2]);
byte[] cipher_text = Base64.getDecoder().decode(result[0]);
SecretKey IV = new SecretKeySpec(decodedIV, 0, decodedIV.length, "AES");
SecretKey key = new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");
byte[] decryptedString = encryptDecrypt(Cipher.DECRYPT_MODE, key.getEncoded(), IV.getEncoded(), cipher_text);
String decryptedMessage = new String(decryptedString);
return decryptedMessage;
}
public static void main(String[] args) throws Exception {
PasswordEncrypt cu = new PasswordEncrypt();
String encryptedmessage = cu.encrypt("fds fasdf asdf asdf adsf asdrtwe trstsr sdffg sdf sgdfg fsd gfsd gfds gsdf gsdf");
System.out.println(encryptedmessage);
String decryptedMessage = cu.decrypt(encryptedmessage);
System.out.println(decryptedMessage);
}
input : fds fasdf asdf asdf adsf asdrtwe trstsr sdffg sdf sgdfg fsd gfsd gfds gsdf gsdf
op : h8Auwmfp98BPkIfjrMFt0myxwi/PSy+/g9Js3EOv31WC12mxg3KaimoTfpFO8Sc9e73kOhYpP0eoxigXf4dAXgqCVwqzT6tqUqm+6aDJKto=javaxeW6Fm9uf7kSI2OXPnyPr1g==javaxnhPcL3vzPWr2BfcmTKSsLQ==

Getting error "Input length must be multiple of 16 when decrypting with padded cipher"

im trying to encrypt and decrypt some data, when i go to run decrypt i get the error Input length must be multiple of 16 when decrypting with padded cipher.
Here is my Java class;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import com.thoughtworks.xstream.core.util.Base64Encoder;
public class passwordEncoder {
private static final String ALGORITHM = "AES";
private static final String myEncryptionKey = "ThisIsFoundation";
private static final String UNICODE_FORMAT = "UTF8";
public static String encrypt(String valueToEnc) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGORITHM);
c.init(Cipher.ENCRYPT_MODE, key);
byte[] encValue = c.doFinal(valueToEnc.getBytes(UNICODE_FORMAT));
//String encryptedValue = new Base64Encoder().encode(encValue);
String encryptedValue = new Base64Encoder().encode(encValue);
return encryptedValue;
}
public static String decrypt(String encryptedValue) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGORITHM);
c.init(Cipher.DECRYPT_MODE, key);
byte[] decordedValue = new Base64Encoder().decode(encryptedValue);
byte[] decValue = c.doFinal(decordedValue);
String decryptedValue = new String(decValue);
return decryptedValue;
}
private static Key generateKey() throws Exception {
byte[] keyAsBytes;
keyAsBytes = myEncryptionKey.getBytes(UNICODE_FORMAT);
Key key = new SecretKeySpec(keyAsBytes, ALGORITHM);
return key;
}
}
Any suggestions/help on how i would fix this error would be appreciated.

Encrypt in Java, Decrypt in Data Power

I am currently working in a solution, where I have encrypt a password in Java (Running in Jboss server), and then send to Data Power and de-crypt in DataPower. I able to encrypt the password in Java. I dont have much knowledge in DataPower. I have got the code to decrypt in datapower, but not sure how to send the key to datapower. Can anyone please help me out. The code is like below,
Encryption Code (Java)
package test;
import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.util.ArrayList;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class Test {
private static final String ALGO = "AES";
public static String encrypt(String data,String secretKey) throws Exception {
Key key = generateKey(secretKey);
byte[] ivAES = {(byte)0x22,(byte)0x22,(byte)0x22,(byte)0x22,(byte)0x22,(byte)0x22,(byte)0x22,(byte)0x22,(byte)0x22,(byte)0x22,(byte)0x22,(byte)0x22,(byte)0x22,(byte)0x22,(byte)0x22,(byte)0x22};
IvParameterSpec ivspec = new IvParameterSpec(ivAES);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, ivspec);
byte[] encVal = cipher.doFinal(data.getBytes());
byte[] finalByte=copyBytes(encVal, ivAES);
String encryptedValue = new BASE64Encoder().encode(finalByte);
return encryptedValue;
}
public static String decrypt(String encryptedData,String secretKey) throws Exception {
Key key = generateKey(secretKey);
byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedData);
ArrayList<byte[]> al = retreiveIv(decordedValue);
byte[] data = al.get(0);
byte[] iv = al.get(1);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
byte[] decValue = cipher.doFinal(data);
String decryptedValue = new String(decValue);
return decryptedValue;
}
private static Key generateKey(String secretKey) throws Exception {
Key key = new SecretKeySpec(secretKey.getBytes(), ALGO);
return key;
}
private static byte[] copyBytes(byte[] encVal, byte[] iv) throws Exception {
ByteArrayOutputStream os = new ByteArrayOutputStream();
os.write(iv);
os.write(encVal);
return os.toByteArray();
}
private static ArrayList<byte[]> retreiveIv(byte[] combineByte) {
ByteArrayOutputStream iv = new ByteArrayOutputStream(16);
ByteArrayOutputStream data = new ByteArrayOutputStream();
data.write(combineByte, combineByte.length - 16, 16);
iv.write(combineByte, 0, combineByte.length - 16);
ArrayList<byte[]> al = new ArrayList<byte[]>();
al.add(data.toByteArray());
al.add(iv.toByteArray());
return al;
}
public static void main(String[] args) throws Exception{
System.out.println(AESUtil.decrypt(AESUtil.encrypt("Hello", "AVH4TU8AC99dhL2l"), "AVH4TU8AC99dhL2l"));
}
}
Decryption (DataPower)
<xsl:variable name="algorithm">http://www.w3.org/2001/04/xmlenc#aes128-cbc</xsl:variable>
<xsl:variable name="decryptOut"><xsl:value-of select="dp:decrypt-data($algorithm,'name:danadp',$valueToDecrypt)"/></xsl:variable>
Decrypted Value: <xsl:copy-of select="$decryptOut"/>
But, I am not getting how to share the Key object to DataPower that we generated in Java code for encryption.
It will be great, if anyone can help me.
Create a shared secret key object with name 'danadp' and the key copied into a file and imported into the cert:/ folder in the DataPower domain where this code is running.
P.S Remember to prefix the key with "0x" if key is in hex.

Decrypting data on desktop that was encrypted on android

I have an app which encrypts some text strings, and then writes these to a file.
The desktop version of the app is reading the file and decrypts the data. The problem is that whenever I decrypt on the desktop version , I get a "javax.crypto.BadPaddingException: Given final block not properly padded"
Both the app and the desktop are using the same code:
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class SSL {
private final static String HEX = "0123456789ABCDEF";
public static String encrypt(Session current, String cleartext) throws Exception {
byte[] rawKey = getRawKey(current.getCurrentSession().getBytes());
byte[] result = encrypt(rawKey, cleartext.getBytes());
return toHex(result);
}
public static String decrypt(Session current, String encrypted) throws Exception {
byte[] rawKey = getRawKey(current.getCurrentSession().getBytes());
byte[] enc = toByte(encrypted);
byte[] result = decrypt(rawKey, enc);
return new String(result);
}
private static byte[] getRawKey(byte[] seed) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
sr.setSeed(seed);
kgen.init(128, sr); // 192 and 256 bits may not be available
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
return raw;
}
private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(clear);
return encrypted;
}
private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(encrypted);
return decrypted;
}
public static String toHex(String txt) {
return toHex(txt.getBytes());
}
public static String fromHex(String hex) {
return new String(toByte(hex));
}
public static byte[] toByte(String hexString) {
int len = hexString.length()/2;
byte[] result = new byte[len];
for (int i = 0; i < len; i++)
result[i] = Integer.valueOf(hexString.substring(2*i, 2*i+2), 16).byteValue();
return result;
}
public static String toHex(byte[] buf) {
if (buf == null)
return "";
StringBuffer result = new StringBuffer(2*buf.length);
for (int i = 0; i < buf.length; i++) {
appendHex(result, buf[i]);
}
return result.toString();
}
private static void appendHex(StringBuffer sb, byte b) {
sb.append(HEX.charAt((b>>4)&0x0f)).append(HEX.charAt(b&0x0f));
}
}
Why can't I decrypt the data on the desktop version? Are the crypto implementations in Android SDK and java 1.7 different?
Note: If I decrypt the encrypted android data on the android, it works. If I encrypt and decrypt on the desktop, it also works. The problem seems to be somewhere between those two.
I have finally found the whole solution.
There were some major issues, and I would like to explain them here so that more users can find the answer. Firstly, the two things pointed out by Duncan needed to be fixed.
After fixing these issues I still had the same problem, and found out that using a pseudo random number to create the raw key is done differently by different platforms/OS'. If you want to have crossplatform independencies, don't use SHA1PRNG as your key algorithm. Instead, use PBEWithSHA256And256BitAES-CBC-BC. I am using the implementation from BouncyCastle, see below for full crypto code.
import java.io.UnsupportedEncodingException;
import java.security.Security;
import java.security.spec.KeySpec;
import java.util.Random;
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.bouncycastle.jce.provider.BouncyCastleProvider;
public class SSL {
private final static String HEX = "0123456789ABCDEF";
private final static String ENC = "US-ASCII";
private final static int ITERATION = 1337;
private static final String RANDOM_ALGORITHM = "PBEWithSHA256And256BitAES-CBC-BC";
private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
private static final String SECRET_KEY_ALGORITHM = "AES";
private static IvParameterSpec ips;
public static void init(byte[] iv) {
if(iv == null) {
iv = new byte[16];
Random random = new Random();
random.nextBytes(iv);
}
ips = new IvParameterSpec(iv);
Security.addProvider(new BouncyCastleProvider());
}
public static byte[] getCertificate() {
return ips.getIV();
}
public static String encrypt(Session current, String cleartext) throws Exception {
byte[] rawKey = getRawKey(current.getCurrentSession().toCharArray());
byte[] result = encrypt(rawKey, cleartext.getBytes(ENC));
return toHex(result);
}
public static String decrypt(Session current, String encrypted) throws Exception {
byte[] rawKey = getRawKey(current.getCurrentSession().toCharArray());
byte[] enc = toByte(encrypted);
byte[] result = decrypt(rawKey, enc);
return new String(result, ENC);
}
private static byte[] getRawKey(char[] seed) throws Exception {
KeySpec keySpec = new PBEKeySpec(seed, ips.getIV(), ITERATION);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(RANDOM_ALGORITHM);
byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded();
SecretKey secretKey = new SecretKeySpec(keyBytes, "AES");
return secretKey.getEncoded();
}
private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, SECRET_KEY_ALGORITHM);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ips);
byte[] encrypted = cipher.doFinal(clear);
return encrypted;
}
private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, SECRET_KEY_ALGORITHM);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, skeySpec, ips);
byte[] decrypted = cipher.doFinal(encrypted);
return decrypted;
}
public static String toHex(String txt) throws UnsupportedEncodingException {
return toHex(txt.getBytes(ENC));
}
public static String fromHex(String hex) throws UnsupportedEncodingException {
return new String(toByte(hex), ENC);
}
public static byte[] toByte(String hexString) {
int len = hexString.length()/2;
byte[] result = new byte[len];
for (int i = 0; i < len; i++)
result[i] = Integer.valueOf(hexString.substring(2*i, 2*i+2), 16).byteValue();
return result;
}
public static String toHex(byte[] buf) {
if (buf == null)
return "";
StringBuffer result = new StringBuffer(2*buf.length);
for (int i = 0; i < buf.length; i++) {
appendHex(result, buf[i]);
}
return result.toString();
}
private static void appendHex(StringBuffer sb, byte b) {
sb.append(HEX.charAt((b>>4)&0x0f)).append(HEX.charAt(b&0x0f));
}
}
There are at least two problems with your code that will affect its functionality on different platforms:
You must specify a character set when calling getBytes() or new String(...). Without this, the results will be different if your platforms have different default charsets.
You must fully specify your encryption algorithm, e.g. replace "AES" with "AES/CBC/PKCS5Padding" to avoid differences between providers.

Encrypt Decrypt my own key not generated java

I am new to cryptography, so I have a question:
How can I create my own key (let`s say like a string "1234"). Because I need to encrypt a string with a key (defined by me), save the encrypted string in a database and when I want to use it, take it from the database and decrypt it with the key known by me.
I have this code :
import java.security.InvalidKeyException;
import java.security.*;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
public class LocalEncrypter {
private static String algorithm = "PBEWithMD5AndDES";
//private static Key key = null;
private static Cipher cipher = null;
private static SecretKey key;
private static void setUp() throws Exception {
///key = KeyGenerator.getInstance(algorithm).generateKey();
SecretKeyFactory factory = SecretKeyFactory.getInstance(algorithm);
String pass1 = "thisIsTheSecretKeyProvidedByMe";
byte[] pass = pass1.getBytes();
SecretKey key = factory.generateSecret(new DESedeKeySpec(pass));
cipher = Cipher.getInstance(algorithm);
}
public static void main(String[] args)
throws Exception {
setUp();
byte[] encryptionBytes = null;
String input = "1234";
System.out.println("Entered: " + input);
encryptionBytes = encrypt(input);
System.out.println(
"Recovered: " + decrypt(encryptionBytes));
}
private static byte[] encrypt(String input)
throws InvalidKeyException,
BadPaddingException,
IllegalBlockSizeException {
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] inputBytes = input.getBytes();
return cipher.doFinal(inputBytes);
}
private static String decrypt(byte[] encryptionBytes)
throws InvalidKeyException,
BadPaddingException,
IllegalBlockSizeException {
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] recoveredBytes =
cipher.doFinal(encryptionBytes);
String recovered =
new String(recoveredBytes);
return recovered;
}
}
Exception in thread "main" java.security.spec.InvalidKeySpecException: Invalid key spec
at com.sun.crypto.provider.PBEKeyFactory.engineGenerateSecret(PBEKeyFactory.java:114)
at javax.crypto.SecretKeyFactory.generateSecret(SecretKeyFactory.java:335)
at LocalEncrypter.setUp(LocalEncrypter.java:22)
at LocalEncrypter.main(LocalEncrypter.java:28)
A KeyGenerator generates random keys. Since you know the secret key, what you need is a SecretKeyFactory. Get an instance for your algorithm (DESede), and then call its generateSecret méthode with an instance of DESedeKeySpec as argument:
SecretKeyFactory factory = SecretKeyFactory.getInstance("DESede");
SecretKey key = factory.generateSecret(new DESedeKeySpec(someByteArrayContainingAtLeast24Bytes));
Here is a complete example that works. As I said, DESedeKeySpec must be used with the DESede algorithm. Using a DESede key with PBEWithMD5AndDES makes no sense.
public class EncryptionTest {
public static void main(String[] args) throws Exception {
byte[] keyBytes = "1234567890azertyuiopqsdf".getBytes("ASCII");
DESedeKeySpec keySpec = new DESedeKeySpec(keyBytes);
SecretKeyFactory factory = SecretKeyFactory.getInstance("DESede");
SecretKey key = factory.generateSecret(keySpec);
byte[] text = "Hello world".getBytes("ASCII");
Cipher cipher = Cipher.getInstance("DESede");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encrypted = cipher.doFinal(text);
cipher = Cipher.getInstance("DESede");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decrypted = cipher.doFinal(encrypted);
System.out.println(new String(decrypted, "ASCII"));
}
}
Well, I found the solution after combining from here and there. The encrypted result will be formatted as Base64 String for safe saving as xml file.
package cmdCrypto;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.xml.bind.DatatypeConverter;
public class CmdCrypto {
public static void main(String[] args) {
try{
final String strPassPhrase = "123456789012345678901234"; //min 24 chars
String param = "No body can see me";
System.out.println("Text : " + param);
SecretKeyFactory factory = SecretKeyFactory.getInstance("DESede");
SecretKey key = factory.generateSecret(new DESedeKeySpec(strPassPhrase.getBytes()));
Cipher cipher = Cipher.getInstance("DESede");
cipher.init(Cipher.ENCRYPT_MODE, key);
String str = DatatypeConverter.printBase64Binary(cipher.doFinal(param.getBytes()));
System.out.println("Text Encryted : " + str);
cipher.init(Cipher.DECRYPT_MODE, key);
String str2 = new String(cipher.doFinal(DatatypeConverter.parseBase64Binary(str)));
System.out.println("Text Decryted : " + str2);
} catch(Exception e) {
e.printStackTrace();
}
}
}

Categories