I'm using a snippet to decrypt an AES file.
However, i'd like to use a key file instead of a password to decrypt the file.
What changes do i need to make in the code below to make that happen?
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class AESCrypto {
public static String encrypt(String seed, String cleartext) throws Exception {
byte[] rawKey = getRawKey(seed.getBytes());
byte[] result = encrypt(rawKey, cleartext.getBytes());
return Converters.toHex(result);
}
public static String decrypt(String seed, String encrypted) throws Exception {
byte[] rawKey = getRawKey(seed.getBytes());
byte[] enc = Converters.toByte(encrypted);
byte[] result = decrypt(rawKey, enc);
return new String(result);
}
public static byte[] getRawKey(byte[] seed) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
sr.setSeed(seed);
try {
kgen.init(256, sr);
} catch (Exception e) {
// Log.w(LOG, "This device doesn't support 256 bits, trying 192 bits.");
try {
kgen.init(192, sr);
} catch (Exception e1) {
// Log.w(LOG, "This device doesn't support 192 bits, trying 128 bits.");
kgen.init(128, sr);
}
}
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;
}
}
An AES key is little more than 16, 24 or 32 bytes of randomly generated data. So to create a key file, save that amount of random data in it, and use it to instantiate SecretKeySpec(byte[] data, "AES").
Note that for your convenience SecretKeySpec is also a SecretKey.
Related
I am developing an application, where I am encrypting and decrypting a text entered by the user.
But, I am getting the following error:
javax.crypto.IllegalBlockSizeException: last block incomplete in
decryption
below is my code for encryption and decryption. Encryption works perfectly, while I am getting this error while decrypting. Please refer the code below:
public static String fncEncrypt(String strClearText, String strKey) throws Exception{
String strData = "";
try {
SecretKeySpec sKeySpec = new SecretKeySpec(strKey.getBytes(), "Blowfish");
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.ENCRYPT_MODE, sKeySpec);
byte[] encrypted = cipher.doFinal(strClearText.getBytes());
strData = new String(encrypted);
}catch (Exception e){
e.printStackTrace();
}
return strData;
}
public static String fncDecrypt(String strEecrypted, String strKey) throws Exception {
String strData = "";
try {
SecretKeySpec skeySpec = new SecretKeySpec(strKey.getBytes(), "Blowfish");
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(strEecrypted.getBytes());
strData = new String(decrypted);
}catch (Exception e){
e.printStackTrace();
}
return strData;
}
Please respond if you have a solution for this.
You should decode the string instead of encoding the platform specific representation of the string, right at the start of your method.
byte[] base64TextToDecrypt = Base64.decodeBase64(textToDecrypt);
or more precisely:
byte[] bytesToDecrypt = Base64(base64TextToDecrypt);
if you name your variables correctly.
In general, each time you (feel like you have to) use the String.getBytes(): byte[] method or the String(byte[]) constructor you are likely doing something wrong. You should first think about what you are trying to do, and specify a character-encoding if you do need to use it.
In your case, the output in the converted variable is probably character-encoded. So you you could use the following fragment:
String plainText = new String(converted, Charset.forName("UTF8"));
System.out.println(plainText);
instead of what you have now.
Reference : https://stackoverflow.com/a/13274072/8416317
String class method getBytes() or new String(byte bytes[]) encode / decode with Charset.defaultCharset().name(), and some encrypted data would be ignored by encoding with special charset.
you could directly return byte[] by fncEncrypt and input byte[] to fncDecrypt. or encode result with BASE64.
public static byte[] fncEncrypt(String strClearText, String strKey) throws Exception{
byte[] encrypted = null;
try {
SecretKeySpec sKeySpec = new SecretKeySpec(strKey.getBytes(), "Blowfish");
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.ENCRYPT_MODE, sKeySpec);
encrypted = cipher.doFinal(strClearText.getBytes());
} catch (Exception e){
e.printStackTrace();
}
return encrypted;
}
public static String fncDecrypt(byte[] ecrypted, String strKey) throws Exception {
String strData = "";
try {
SecretKeySpec skeySpec = new SecretKeySpec(strKey.getBytes(), "Blowfish");
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(ecrypted);
strData = new String(decrypted);
}catch (Exception e){
e.printStackTrace();
}
return strData;
}
The reason is when you use new String(encrypted) it will not fully encode the bytes to string. Try the code below
public static byte[] fncEncrypt(String strClearText, String strKey) throws Exception{
SecretKeySpec sKeySpec = new SecretKeySpec(strKey.getBytes(), "Blowfish");
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.ENCRYPT_MODE, sKeySpec);
byte[] encrypted = cipher.doFinal(strClearText.getBytes());
return encrypted;
}
public static String fncDecrypt(byte[] encrypted, String strKey) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(strKey.getBytes(), "Blowfish");
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(encrypted);
return new String(decrypted);
}
You can encrypt and decrypt using the code below
String message = "Hello!";
byte[] encrypted = fncEncrypt(message, "key");
String decrypted = fncDecrypt(encrypted, "key");
System.out.println(decrypted);
I need some help validating the below code snippet for Java AES encryption with CBC, PKCS5Padding and IV.
I tested the code and was able to encrypt and decrypt. I have a few queries as described below.
Where should the password be stored as a good convention?
Is the way of appending/retrieving salt and IV bytes to the ciphetext fine?
Any other comments highly appreciated, thanks!
public class Encryption {
private static int iterations = 65536;
private static int keySize = 128;
private static char[] password = "password".toCharArray();
private static String algorithm= "PBKDF2WithHmacSHA1";
private static final String SEPARATOR = "~";
public static void main(String []args) throws Exception {
String filePath = "test.xml";
String fileContent = new String(Files.readAllBytes(Paths.get(filePath)));
String encrMesg = encrypt(fileContent);
System.out.println("Encrypted: " + encrypt(encrMesg));
System.out.println("Decrypted: " + decrypt(encrMesg));
}
public static String encrypt(String plaintext) throws Exception {
byte[] saltBytes = getSalt().getBytes();
SecretKeyFactory skf = SecretKeyFactory.getInstance(algorithm);
PBEKeySpec spec = new PBEKeySpec(password, 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();
byte[] ivBytes = params.getParameterSpec(IvParameterSpec.class).getIV();
byte[] cipherText = cipher.doFinal(String.valueOf(plaintext).getBytes("UTF-8"));
return DatatypeConverter.printBase64Binary(ivBytes)+SEPARATOR+DatatypeConverter.printBase64Binary(saltBytes)
+SEPARATOR+DatatypeConverter.printBase64Binary(cipherText);
}
public static String decrypt(String encryptedText) throws Exception {
System.out.println(encryptedText);
String[] encryptedArr = encryptedText.split(SEPARATOR);
byte[] ivBytes = DatatypeConverter.parseBase64Binary(new String(encryptedArr[0]));
byte[] salt = DatatypeConverter.parseBase64Binary(new String(encryptedArr[1]));
byte[] encryptedTextBytes = DatatypeConverter.parseBase64Binary(new String(encryptedArr[2]));
SecretKeyFactory skf = SecretKeyFactory.getInstance(algorithm);
PBEKeySpec spec = new PBEKeySpec(password, salt, 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 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);
}
}
Queries
Where should the password be stored as a good convention?
Symmetric keys should go preferably to a vault. Otherwise they should go on a keystore, but then you have the issue of securing the keystore password.
Is the way of appending/retrieving Salt and IV bytes to the Cipher
text is fine?
Salt should be generated with:
SecureRandom random = SecureRandom.getInstanceStrong();
Otherwise you are using weaker entropy pools (i.e. /dev/urandom in linux) to generate your secure numbers, and that leads to weak keys that can be more easily broken.
Any other comments highly appreciated, thanks!
You should consistently use the same encoding when dealing with String conversion, i.e., .getBytes("UTF-8") to avoid issues. You don't use it when converting the salt for example.
I'm new to cryptography and I'm attempting to create a simple AES encryption program and base64 enconding. The program seems to encrypt and decrypt my message string as it should but for some reason it shows me the exception java.lang.IllegalArgumentException: Illegal base64 character 20 in the decrypt method but maybe it has something to do with the encryption..
After searching for a while I couldn't find the reason for this. I would appreciate if someone could point out any mistakes in my code that could lead to this error!
public class AES_encryption {
private static SecretKey skey;
public static Cipher cipher;
public static void main(String[] args) throws Exception{
String init_vector = "RndInitVecforCBC";
String message = "Encrypt this?!()";
String ciphertext = null;
//Generate Key
skey = generateKey();
//Create IV necessary for CBC
IvParameterSpec iv = new IvParameterSpec(init_vector.getBytes());
//Set cipher to AES/CBC/
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
try{
ciphertext = encrypt(skey, iv, message);
}
catch(Exception ex){
System.err.println("Exception caught at encrypt method!" + ex);
}
System.out.println("Original Message: " + message + "\nCipher Text: " + ciphertext);
try{
message = decrypt(skey, iv, message);
}
catch(Exception ex){
System.err.println("Exception caught at decrypt method! " + ex);
}
System.out.println("Original Decrypted Message: " + message);
}
private static SecretKey generateKey(){
try {
KeyGenerator keygen = KeyGenerator.getInstance("AES");
keygen.init(128);
skey = keygen.generateKey();
}
catch(NoSuchAlgorithmException ex){
System.err.println(ex);
}
return skey;
}
private static String encrypt(SecretKey skey, IvParameterSpec iv, String plaintext) throws Exception{
//Encodes plaintext into a sequence of bytes using the given charset
byte[] ptbytes = plaintext.getBytes(StandardCharsets.UTF_8);
//Init cipher for AES/CBC encryption
cipher.init(Cipher.ENCRYPT_MODE, skey, iv);
//Encryption of plaintext and enconding to Base64 String so it can be printed out
byte[] ctbytes = cipher.doFinal(ptbytes);
Base64.Encoder encoder64 = Base64.getEncoder();
String ciphertext = new String(encoder64.encode(ctbytes), "UTF-8");
return ciphertext;
}
private static String decrypt(SecretKey skey, IvParameterSpec iv, String ciphertext) throws Exception{
//Decoding ciphertext from Base64 to bytes[]
Base64.Decoder decoder64 = Base64.getDecoder();
byte[] ctbytes = decoder64.decode(ciphertext);
//Init cipher for AES/CBC decryption
cipher.init(Cipher.DECRYPT_MODE, skey, iv);
//Decryption of ciphertext
byte[] ptbytes = cipher.doFinal(ctbytes);
String plaintext = new String(ptbytes);
return plaintext;
}
}
The issue is because you decrypt the message not the encrypted message!
decrypt(skey, iv, message) should probably be decrypt(skey, iv, ciphertext)
I am using the below code to create a 128 bit AES cipher,
String initializer = "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000";
byte[] initializer2 = new BigInteger(initializer, 2).toByteArray();
String encrypt = encrypt(binary_string_firsthalf, initializer2);
public static String encrypt(String plainText, byte[] key) {
try {
SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] cipherText = cipher.doFinal(plainText.getBytes("UTF8"));
String encryptedString = new String(Base64.encode(cipherText));
return encryptedString;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
But the code is returning a exception saying invalid AES key length.
How to create a cipher using 128 0's.
byte[] initializer2 = new byte[16];
is all you need to initialize a byte array with the default value of 0x00.
Don't use a static predictable key such as all 0x00 bytes for actual encryption.
So I'm writing a program to encrypt and decrypt text files but I seem to be always getting this error when I use an encrypthion other than "Blowfish" (e.g. "Blowfish/CBC/PKCS5Padding"). The excepthiong I get is:
Exception in thread "main" java.security.NoSuchAlgorithmException: Blowfish/CBC/PKCS5Padding KeyGenerator not available
at javax.crypto.KeyGenerator.<init>(DashoA13*..)
at javax.crypto.KeyGenerator.getInstance(DashoA13*..)
at Encryptor.<init>(Encryptor.java:87)
at Encryptor.main(Encryptor.java:30)
A portion of my code:
import java.security.MessageDigest;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class Encryptor2 {
private IvParameterSpec ivSpec;
private SecretKeySpec keySpec;
private Cipher cipher;
public static void main(String[] args) throws Exception {
Encryptor2 e = new Encryptor2(
"averylongtext!#$##$##$#*&(*&}{23432432432dsfsdf");
String enc = e.encrypt("john doe");
String dec = e.decrypt(enc);
}
public Encryptor2(String pass) throws Exception {
// setup AES cipher in CBC mode with PKCS #5 padding
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
// setup an IV (initialization vector) that should be
// randomly generated for each input that's encrypted
byte[] iv = new byte[cipher.getBlockSize()];
new SecureRandom().nextBytes(iv);
ivSpec = new IvParameterSpec(iv);
// hash keyString with SHA-256 and crop the output to 128-bit for key
MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.update(pass.getBytes());
byte[] key = new byte[16];
System.arraycopy(digest.digest(), 0, key, 0, key.length);
keySpec = new SecretKeySpec(key, "AES");
}
public String encrypt(String original) throws Exception {
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
byte[] encrypted = cipher.doFinal(original.getBytes("UTF-8"));
System.out.println("encrypted: `" + new String(encrypted) + "`");
return new String(encrypted);
}
public String decrypt(String encrypted) throws Exception {
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
byte[] decrypted = cipher.doFinal(encrypted.getBytes("UTF-8"));
System.out.println("decrypted: `" + new String(decrypted, "UTF-8")
+ "`");
return new String(decrypted, "UTF-8");
}
}
But now it fails with Input length must be multiple of 16 when decrypting with padded cipher
The additional parameters that you're specifying with the algorithm are meant for Cipher. For KeyGenerator and SecretKeySpec you only specify the algorithm. The other parameters are for the cipher mode of operation and padding to be used. For example, if you're using Blowfish in CBC mode with PKCS #5 padding you want:
KeyGenerator keyGen = KeyGenerator.getInstance("Blowfish");
Cipher cipher = Cipher.getInstance("Blowfish/CBC/PKCS5Padding");
See Encrypting and Decrypting Using Java: Unable to get same output for an example. It uses the same mode and padding as you have. The only difference is that uses AES instead of Blowfish, however it works exactly the same.