Encryption and Decryption in Java using AES - java

How to Encrypt and Decrypt in Java using AES
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
public class Encryption {
public static void main(String args[]) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException{
String t = "Testing";
byte[] dataToSend = t.getBytes();
byte[] key = new byte[16];
Cipher c = Cipher.getInstance("AES");
SecretKeySpec k = new SecretKeySpec(key, "AES");
c.init(Cipher.ENCRYPT_MODE, k);
byte[] encryptedData = c.doFinal(dataToSend);
System.out.println(encryptedData);
byte[] key2 = new byte[16];
byte[] encryptedData2 = encryptedData;
Cipher c2 = Cipher.getInstance("AES");
SecretKeySpec k2 =
new SecretKeySpec(key2, "AES");
c2.init(Cipher.DECRYPT_MODE, k2);
byte[] data = c.doFinal(encryptedData);
System.out.println(data);
}
}

Since the problem is not specified explicitly, I am pointing out the obvious errors with the presumption that 'Testing' encrypted should print 'Testing' once decrypted.
AES is a symmetric key algorithm, hence you have to use the same key for encrypting and decrypting (k2 should not be there at all)
c.doFinal of the encrypted data doesn't make much sense, this should be reference to your Cipher DECRYPT_MODE -> c2
Hence, change:
c2.init(Cipher.DECRYPT_MODE, k2);
To:
c2.init(Cipher.DECRYPT_MODE, k);
And change:
byte[] data = c.doFinal(encryptedData);
To:
byte[] data = c2.doFinal(encryptedData);
To print the final outcome:
Change:
System.out.println(data);
To:
System.out.println(new String(data));

Related

How can I decrypt text encrypted using this code?

I found this code on a website. I can't understand how to decode this. Can you help me?
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
public class AES {
public static String encrypt(String strToEncrypt) throws Exception {
byte[] plaintext = strToEncrypt.getBytes("UTF-8");
KeyGenerator keygen = KeyGenerator.getInstance("AES");
keygen.init(256);
SecretKey key = keygen.generateKey();
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] ciphertext = cipher.doFinal(plaintext);
return Base64.getEncoder().encodeToString(ciphertext);
}
}
Welcome to Stackoverflow. Below you find a full working example of an AES CBC String en-/decryption. Please note that you need to store the randmly created key & initialization vectore securely to (later) encrypted data because otherwise there is (realy) NO way to recover your data. The same key and iv needs to be used for encryption and decryption.
As the key & iv are byte arrays I encoded them to Base64 for a better storage.
Security warning: This is a simple example to demonstrate AES CBC en-/decryption without any proper exception handling.
The code is for educational purposes only and should not be used in production!
result:
AES CBC String Encryption with random key + iv
This is a simple example to demonstrate AES CBC en-/decryption without any proper exception handling.
The code is for educational purposes only and should not be used in production.
save the key and iv securely, without the data it will be NOT possible to decrypt !!
key in Base64-format: Nf41yG0F+MdFQnp3p3mIrWOk+2kxQ/LmyVcHKEKi5sQ=
iv in Base64-format: yICmqsMaIdwsYsUDUsLWnA==
plaintext: The quick brown fox jumps over the lazy dog
ciphertext: PJNEV3H3Zh3TQx7B9jpg29gV59LgJ6baOpNM82dMOpPClJouYnq+hKVUQTDEkkdI
decryptedtext: The quick brown fox jumps over the lazy dog
code:
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
public class AesCbcTextEncryptionRandomKeyIv {
public static void main(String[] args) throws NoSuchPaddingException, InvalidKeyException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException {
System.out.println("AES CBC String Encryption with random key + iv");
System.out.println("This is a simple example to demonstrate AES CBC en-/decryption without any proper exception handling.");
System.out.println("The code is for educational purposes only and should not be used in production.\n");
String plaintext = "The quick brown fox jumps over the lazy dog";
// generate a random key & initialization vector
byte[] key = new byte[32]; // key for aes 256 encryption, 32 byte length
byte[] iv = new byte[16]; // initialization vector with 16 byte length
SecureRandom secureRandom = new SecureRandom();
secureRandom.nextBytes(key);
secureRandom.nextBytes(iv);
System.out.println("save the key and iv securely, without the data it will be NOT possible to decrypt !!");
// convert key & iv in base64 format for storage reasons
String keyBase64 = Base64.getEncoder().encodeToString(key);
String ivBase64 = Base64.getEncoder().encodeToString(iv);
System.out.println("key in Base64-format: " + keyBase64);
System.out.println("iv in Base64-format: " + ivBase64);
// encryption
String ciphertext = encrypt(keyBase64, ivBase64, plaintext);
System.out.println("plaintext: " + plaintext);
System.out.println("ciphertext: " + ciphertext);
// decryption
String decryptedtext = decrypt(keyBase64, ivBase64, ciphertext);
System.out.println("decryptedtext: " + decryptedtext);
}
public static String encrypt(String keyBase64, String ivBase64, String plaintext)
throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException,
InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.getDecoder().decode(keyBase64), "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(Base64.getDecoder().decode(ivBase64));
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
return Base64.getEncoder().encodeToString(cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8)));
}
public static String decrypt(String keyBase64, String ivBase64, String ciphertext)
throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException,
InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.getDecoder().decode(keyBase64), "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(Base64.getDecoder().decode(ivBase64));
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
return new String(cipher.doFinal(Base64.getDecoder().decode(ciphertext)), StandardCharsets.UTF_8);
}
}

Node JS encryption code to Java encryption code

I'm trying to find the similar java code for the below Node JS code,
Node JS Code:
var crypto = require('crypto');
var mykey = crypto.createCipher('aes-128-ecb', 'XXXXXXXX00000000');
var mystr = mykey.update('HelloWorld', 'utf8', 'hex')
mystr += mykey.final('hex');
console.log(mystr);
Encryption Result: ce25d577457cf8113fa4d9eb16379529
Java Code:
public static String toHex(String arg) throws UnsupportedEncodingException {
return String.format("%x", new BigInteger(1, arg.getBytes("UTF-8")));
}
public static void main(String args[]) throws Exception{
byte[] key = "XXXXXXXX".getBytes();
String message = "HelloWorld";
try {
key = Arrays.copyOf(key, 16);
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte encstr[] = cipher.update(message.getBytes());
String encData = new String(encstr, "UTF-8");
encData = toHex(encData);
byte encstr2[] = cipher.doFinal();
String encData2 = new String(encstr2);
encData = encData + toHex(encData2);
System.out.println(encData);
} catch (NoSuchAlgorithmException nsae) {
throw new Exception("Invalid Java Version");
} catch (NoSuchPaddingException nse) {
throw new Exception("Invalid Key");
}
}
Encryption Result: 056efbfbdefbfbd7c7760efbfbdefbfbdefbfbd39262cefbfbdefbfbd5166
Taking up the comments of #Robert and #Topaco I wrote a simple decryption program that is working for the given password 'XXXXXXXX00000000'.
Please keep in mind that this progrsm is using UNSECURE AES ECB mode and UNSECURE MD5 hash algorithm.
The program does NOT provide any proper exception handling.
This is the result:
ciphertext Java: ce25d577457cf8113fa4d9eb16379529
ciphertext NodeJS: ce25d577457cf8113fa4d9eb16379529
My code:
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MainSo {
public static void main(String[] args) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
System.out.println("https://stackoverflow.com/questions/63263081/node-js-encryption-code-to-java-encryption-code");
String plaintext = "HelloWorld";
String keyString = "XXXXXXXX00000000"; // 16 chars
byte[] key = keyString.getBytes(StandardCharsets.UTF_8);
// md5 hashing is unsecure !!
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] keyMd5 = md.digest(key);
// aes ecb mode encryption is unsecure
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
SecretKeySpec secretKeySpec = new SecretKeySpec(keyMd5, "AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] ciphertext = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
System.out.println("ciphertext Java: " + bytesToHex(ciphertext));
System.out.println("ciphertext NodeJS: " + "ce25d577457cf8113fa4d9eb16379529");
}
private static String bytesToHex(byte[] bytes) {
// service method for displaying a byte array as hex string
StringBuffer result = new StringBuffer();
for (byte b : bytes) result.append(Integer.toString((b & 0xff) + 0x100, 16).substring(1));
return result.toString();
}
}

BadPaddingException just with letters like "o", "b", "c"

I'm making a program which works with messages cryptography by Socket. But, when in my messages has a "o", or "b", or "c" and another letters, i receives that Exception in the decrypto moment.
Exception in thread "main" javax.crypto.BadPaddingException: Given final block not properly padded. Such issues can arise if a bad key is used during decryption.
at com.sun.crypto.provider.CipherCore.unpad(CipherCore.java:975)
at com.sun.crypto.provider.CipherCore.fillOutputBuffer(CipherCore.java:1056)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:853)
at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:446)
at javax.crypto.Cipher.doFinal(Cipher.java:2164)
at teste1.Decrypt.decrypt(Decrypt.java:15)
at teste1.Server.main(Server.java:24)
Yep, my message arrives completed with all the characters, so i don't think in some character was lost in the trasmission. So i don't really know what's the problem, because i've tried to changes a lot of things, but i continued recieving this Exception.
Decrypt class:
package teste1;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.spec.IvParameterSpec;
public class Decrypt{
String IV = "AAAAAAAAAAAAAAAA";
public String decrypt(String str, String keys) throws Exception{
Cipher decrypt = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE");
SecretKeySpec key = new SecretKeySpec(keys.getBytes("UTF-8"), "AES");
decrypt.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(IV.getBytes("UTF-8")));
return new String(decrypt.doFinal(str.getBytes()),"UTF-8");
}
}
If wants the encrypt class too:
package teste1;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class Encrypt {
String IV = "AAAAAAAAAAAAAAAA";
public byte[] encrypt(String menE, String keys) throws Exception {
Cipher encrypt = Cipher.getInstance("AES/EBC/PKCS5Padding", "SunJCE");
SecretKeySpec key = new SecretKeySpec(keys.getBytes("UTF-8"), "AES");
encrypt.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(IV.getBytes("UTF-8")));
return encrypt.doFinal(menE.getBytes());
}
}
That happens because Strings change your bytes, you should really use Base64
if strings are a must.
If you want to test that run this code:
byte[] aByte = {-45};
System.out.println(Arrays.toString(new String(aByte, StandardCharsets.UTF_8).getBytes(StandardCharsets.UTF_8)));
It will output: [-17, -65, -67] (which is not -45).
Anyways so a few tips for you:
You cannot encrypt with "ECB" and decrypt with "CBC".
An IV should not be a constant. you should generate a new IV for every message and send it along with the message.
Don't specify "UTF-8" use StandardCharsets.UTF_8 (note if using android: StandardCharsets.UTF-8 is API 19+ so you should have a constant for Charset.forName("UTF-8"))
Here is some example code for how to do it with Base64:
public byte[] encrypt(String message, String key, String iv) throws Exception {
Cipher encrypt = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE");
SecretKeySpec secretKey = new SecretKeySpec(Base64.getDecoder().decode(key), "AES");
encrypt.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(Base64.getDecoder().decode(iv)));
return encrypt.doFinal(/*Get bytes from your message*/message.getBytes(StandardCharsets.UTF_8));
}
public String decrypt(String encryptedMessage, String key, String iv) throws Exception{
Cipher decrypt = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE");
SecretKeySpec secretKey = new SecretKeySpec(Base64.getDecoder().decode(key), "AES");
decrypt.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(Base64.getDecoder().decode(iv)));
return new String(decrypt.doFinal(Base64.getDecoder().decode(encryptedMessage)), StandardCharsets.UTF_8);
}
And run it with
//your message
String message = "Hello World!";
//generate a new AES key. (an AES key is just a random sequence 16 bytes)
SecureRandom random = new SecureRandom();
byte[] aesKey = new byte[16];
random.nextBytes(aesKey);
//generate a new initialization vector (iv) which is also a random sequence of 16 bytes.
byte[] iv = new byte[16];
random.nextBytes(iv);
String aesKeyAsString = Base64.getEncoder().encodeToString(aesKey);
String ivAsString = Base64.getEncoder().encodeToString(iv);
//encrypt
byte[] encrypted = encrypt(message, aesKeyAsString, ivAsString);
//enocde your encrypted byte[] to String
String encryptedString = Base64.getEncoder().encodeToString(encrypted);
//decrypt
String decrypted = decrypt(encryptedString, aesKeyAsString, ivAsString);
//print your results
System.out.println("Encrypted: " + encryptedString + " Decrypted: " + decrypted);
Outputs:
Encrypted: |encrypted string depended on the generated key and iv| Decrypted: Hello World!
You can also use the more efficient way and use byte[] instead of Strings but it's your choice.

AES DEcryption in CTR mode (Java)

I have these information:
CTR key: 36f18357be4dbd77f050515c73fcf9f2
CTR Ciphertext 1:69dda8455c7dd4254bf353b773304eec0ec7702330098ce7f7520d1cbbb20fc3\
88d1b0adb5054dbd7370849dbf0b88d393f252e764f1f5f7ad97ef79d59ce29f5f51eeca32eabedd9afa9329
Note that the 16-byte encryption IV is chosen at random and is prepended to the ciphertext. And the text is encrypted with AES in CTR mode.
I have to discover the plaintext
To do this I have written a short Java program but it doesn't work and I don't find why :/
This is the Java program
import java.nio.charset.Charset;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class AES {
/**
* #param args
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
//Dernier exemple CTR mode
//Clé 16 bits
byte[] keyBytes = new byte[] { (byte)0x36,(byte)0xf1,(byte)0x83,(byte)0x57,(byte)0xbe,(byte)0x4d,(byte)0xbd,(byte)0x77,(byte)0xf0,(byte)0x50,(byte)0x51,(byte)0x5c,0x73,(byte)0xfc,(byte)0xf9,(byte)0xf2};
//IV 16 bits (préfixe du cipherText)
byte[] ivBytes = new byte[] {(byte)0x69,(byte)0xdd,(byte)0xa8,(byte)0x45,(byte)0x5c,(byte)0x7d,(byte)0xd4,(byte)0x25,(byte)0x4b,(byte)0xf3,(byte)0x53,(byte)0xb7,(byte)0x73,(byte)0x30,(byte)0x4e,(byte)0xec};
//Initialisation
SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
//Mode
Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");
byte[] cipherText = new byte[] {(byte)0x0e,(byte)0xc,(byte)0x77,(byte)0x02,(byte)0x33,(byte)0x00,(byte)0x98,(byte)0xce,(byte)0x7f,(byte)0x75,(byte)0x20,(byte)0xd1,(byte)0xcb,(byte)0xbb,(byte)0x20,(byte)0xfc,(byte)0x38,(byte)0x8d,(byte)0x1b,(byte)0x0a,(byte)0xdb,(byte)0x50,(byte)0x54,(byte)0xdb,(byte)0xd7,(byte)0x37,(byte)0x08,(byte)0x49,(byte)0xdb,(byte)0xf0,(byte)0xb8,(byte)0x8d,(byte)0x39,(byte)0x3f,(byte)0x25,(byte)0x2e,(byte)0x76,(byte)0x4f,(byte)0x1f,(byte)0x5f,(byte)0x7a,(byte)0xd9,(byte)0x7e,(byte)0xf7,(byte)0x9d,(byte)0x59,(byte)0xce,(byte)0x29,(byte)0xf5,(byte)0xf5,(byte)0x1e,(byte)0xec,(byte)0xa3,(byte)0x2e,(byte)0xab,(byte)0xed,(byte)0xd9,(byte)0xaf,(byte)0xa9,(byte)0x32,(byte)0x29};
cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
byte [] original = cipher.doFinal(cipherText);
String plaintext = new String(original);
System.out.println("plaintext: " + plaintext );
}
}
The result is => plaintext: CŸUnfpL¨KH¹)VPÅ|ÉÒ9}FÅgÿ žQ3Š®¹zÛ˜ˆ±<þãh¤ÔÆË“M±§|#+0H5§
So it seems to be wrong
Thank you in advance :)
There could be other problems, but the cipher text in your question, after the 16 first bytes, starts with 0ec770, whereas the cipher text in the Java code starts with
0x0e, 0xc, 0x77
They don't match.

How to fix the NoSuchAlgorithmException in Java when using Blowfish?

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.

Categories