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==
Related
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)
}
}
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.
I found a guide for implementing AES encryption/decryption in Java and tried to understand each line as I put it into my own solution. However, I don't fully understand it and am having issues as a result. The end goal is to have passphrase based encryption/decryption. I've read other articles/stackoverflow posts about this, but most do not provide enough explanation (I am very new to crypto in Java)
My main issues right now are that even when I set byte[] saltBytes = "Hello".getBytes();
I still get a different Base64 result in the end (char[] password is random each time, but I read that it is safer to leave passwords in char[] form. My other problem is that when the program gets to decrypt(), I get a NullPointerException at
byte[] saltBytes = salt.getBytes("UTF-8");
Thank you in advance for any help/advice you can give me.
The code in question:
import java.security.AlgorithmParameters;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
public class EncryptionDecryption {
private static String salt;
private static int iterations = 65536 ;
private static int keySize = 256;
private static byte[] ivBytes;
public static void main(String []args) throws Exception {
char[] message = "PasswordToEncrypt".toCharArray();
System.out.println("Message: " + message.toString());
System.out.println("Encrypted: " + encrypt(message));
System.out.println("Decrypted: " + decrypt(encrypt(message).toCharArray()));
}
public static String encrypt(char[] plaintext) throws Exception {
salt = getSalt();
byte[] saltBytes = salt.getBytes();
SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
PBEKeySpec spec = new PBEKeySpec(plaintext, saltBytes, iterations, keySize);
SecretKey secretKey = skf.generateSecret(spec);
SecretKeySpec secretSpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretSpec);
AlgorithmParameters params = cipher.getParameters();
ivBytes = params.getParameterSpec(IvParameterSpec.class).getIV();
byte[] encryptedTextBytes = cipher.doFinal(plaintext.toString().getBytes("UTF-8"));
return DatatypeConverter.printBase64Binary(encryptedTextBytes);
}
public static String decrypt(char[] encryptedText) throws Exception {
byte[] saltBytes = salt.getBytes("UTF-8");
byte[] encryptedTextBytes = DatatypeConverter.parseBase64Binary(encryptedText.toString());
SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
PBEKeySpec spec = new PBEKeySpec(encryptedText, saltBytes, iterations, keySize);
SecretKey secretkey = skf.generateSecret(spec);
SecretKeySpec secretSpec = new SecretKeySpec(secretkey.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretSpec, new IvParameterSpec(ivBytes));
byte[] decryptedTextBytes = null;
try {
decryptedTextBytes = cipher.doFinal(encryptedTextBytes);
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return decryptedTextBytes.toString();
}
public static String getSalt() throws Exception {
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
byte[] salt = new byte[20];
sr.nextBytes(salt);
return salt.toString();
}
}
I think that you are making two mistakes :)
I've corrected your sample code to make it work :
import java.security.AlgorithmParameters;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
public class EncryptionDecryption {
private static String salt;
private static int iterations = 65536 ;
private static int keySize = 256;
private static byte[] ivBytes;
private static SecretKey secretKey;
public static void main(String []args) throws Exception {
salt = getSalt();
char[] message = "PasswordToEncrypt".toCharArray();
System.out.println("Message: " + String.valueOf(message));
System.out.println("Encrypted: " + encrypt(message));
System.out.println("Decrypted: " + decrypt(encrypt(message).toCharArray()));
}
public static String encrypt(char[] plaintext) throws Exception {
byte[] saltBytes = salt.getBytes();
SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
PBEKeySpec spec = new PBEKeySpec(plaintext, saltBytes, iterations, keySize);
secretKey = skf.generateSecret(spec);
SecretKeySpec secretSpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretSpec);
AlgorithmParameters params = cipher.getParameters();
ivBytes = params.getParameterSpec(IvParameterSpec.class).getIV();
byte[] encryptedTextBytes = cipher.doFinal(String.valueOf(plaintext).getBytes("UTF-8"));
return DatatypeConverter.printBase64Binary(encryptedTextBytes);
}
public static String decrypt(char[] encryptedText) throws Exception {
System.out.println(encryptedText);
byte[] encryptedTextBytes = DatatypeConverter.parseBase64Binary(new String(encryptedText));
SecretKeySpec secretSpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretSpec, new IvParameterSpec(ivBytes));
byte[] decryptedTextBytes = null;
try {
decryptedTextBytes = cipher.doFinal(encryptedTextBytes);
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return new String(decryptedTextBytes);
}
public static String getSalt() throws Exception {
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
byte[] salt = new byte[20];
sr.nextBytes(salt);
return new String(salt);
}
}
The first mistake is that you generate 2 different salts (when using the encrypt method), so encrypted/decrypted logs were differents (logical, but the decryption would still work because you are calling the decryption directly after encryption).
The second mistake was for the secret key. You need to generate a secret key when you are encrypting, but not decrypting. To put it more simply, it is as if i was encrypting with the password "encrypt" and that you are trying to decrypt it with the password "decrypt".
I would advise you to generate every random stuff (such as private key, salt etc on startup). But beware that when you'll stop your app, you won't be able to decrypt old stuff unless getting the exact same random stuff.
Hope I helped :)
Regards,
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.
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();
}
}
}