Java AES encryption and decryption - java

I would like to encrypt and decrypt a password using 128 bit AES encryption with 16 byte key. I am getting javax.crypto.BadPaddingException error while decrypting the value. Am I missing anything while decrypting?
public static void main(String args[]) {
Test t = new Test();
String encrypt = new String(t.encrypt("mypassword"));
System.out.println("decrypted value:" + t.decrypt("ThisIsASecretKey", encrypt));
}
public String encrypt(String value) {
try {
byte[] raw = new byte[]{'T', 'h', 'i', 's', 'I', 's', 'A', 'S', 'e', 'c', 'r', 'e', 't', 'K', 'e', 'y'};
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(value.getBytes());
System.out.println("encrypted string:" + (new String(encrypted)));
return new String(skeySpec.getEncoded());
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalBlockSizeException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
} catch (BadPaddingException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidKeyException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchPaddingException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
public String decrypt(String key, String encrypted) {
try {
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(skeySpec.getEncoded(), "AES"));
//getting error here
byte[] original = cipher.doFinal(encrypted.getBytes());
return new String(original);
} catch (IllegalBlockSizeException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
} catch (BadPaddingException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidKeyException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchPaddingException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
Error message
encrypted string:�Bj�.�Ntk�F�`�
encrypted key:ThisIsASecretKey
decrypted value:null
May 25, 2012 12:54:02 PM bean.Test decrypt
SEVERE: null
javax.crypto.BadPaddingException: Given final block not properly padded
at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
at com.sun.crypto.provider.AESCipher.engineDoFinal(DashoA13*..)
at javax.crypto.Cipher.doFinal(DashoA13*..)
at bean.Test.decrypt(Test.java:55)
at bean.Test.main(Test.java:24)
Finally I am using following Solution based on #QuantumMechanic answer
public class Test {
public String encryptionKey;
public static void main(String args[]) {
Test t = new Test();
String encrypt = t.encrypt("mypassword");
System.out.println("decrypted value:" + t.decrypt(t.encryptionKey, encrypt));
}
public String encrypt(String value) {
try {
// Get the KeyGenerator
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(256);
// Generate the secret key specs.
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
String key = new Base64().encodeAsString(raw);
this.encryptionKey = key;
System.out.println("------------------Key------------------");
System.out.println(key);
System.out.println("--------------End of Key---------------");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
String encrypt = (new Base64()).encodeAsString(cipher.doFinal(value.getBytes()));
System.out.println("encrypted string:" + encrypt);
return encrypt;
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalBlockSizeException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
} catch (BadPaddingException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidKeyException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchPaddingException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
public String decrypt(String key, String encrypted) {
try {
Key k = new SecretKeySpec(Base64.getDecoder().decode(key), "AES");
Cipher c = Cipher.getInstance("AES");
c.init(Cipher.DECRYPT_MODE, k);
byte[] decodedValue = Base64.getDecoder().decode(encrypted);
byte[] decValue = c.doFinal(decodedValue);
String decryptedValue = new String(decValue);
return decryptedValue;
} catch (IllegalBlockSizeException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
} catch (BadPaddingException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidKeyException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchPaddingException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
}

If for a block cipher you're not going to use a Cipher transformation that includes a padding scheme, you need to have the number of bytes in the plaintext be an integral multiple of the block size of the cipher.
So either pad out your plaintext to a multiple of 16 bytes (which is the AES block size), or specify a padding scheme when you create your Cipher objects. For example, you could use:
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
Unless you have a good reason not to, use a padding scheme that's already part of the JCE implementation. They've thought out a number of subtleties and corner cases you'll have to realize and deal with on your own otherwise.
Ok, your second problem is that you are using String to hold the ciphertext.
In general,
String s = new String(someBytes);
byte[] retrievedBytes = s.getBytes();
will not have someBytes and retrievedBytes being identical.
If you want/have to hold the ciphertext in a String, base64-encode the ciphertext bytes first and construct the String from the base64-encoded bytes. Then when you decrypt you'll getBytes() to get the base64-encoded bytes out of the String, then base64-decode them to get the real ciphertext, then decrypt that.
The reason for this problem is that most (all?) character encodings are not capable of mapping arbitrary bytes to valid characters. So when you create your String from the ciphertext, the String constructor (which applies a character encoding to turn the bytes into characters) essentially has to throw away some of the bytes because it can make no sense of them. Thus, when you get bytes out of the string, they are not the same bytes you put into the string.
In Java (and in modern programming in general), you cannot assume that one character = one byte, unless you know absolutely you're dealing with ASCII. This is why you need to use base64 (or something like it) if you want to build strings from arbitrary bytes.

import javax.crypto.*;
import java.security.*;
public class Java {
private static SecretKey key = null;
private static Cipher cipher = null;
public static void main(String[] args) throws Exception
{
Security.addProvider(new com.sun.crypto.provider.SunJCE());
KeyGenerator keyGenerator =
KeyGenerator.getInstance("DESede");
keyGenerator.init(168);
SecretKey secretKey = keyGenerator.generateKey();
cipher = Cipher.getInstance("DESede");
String clearText = "I am an Employee";
byte[] clearTextBytes = clearText.getBytes("UTF8");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] cipherBytes = cipher.doFinal(clearTextBytes);
String cipherText = new String(cipherBytes, "UTF8");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedBytes = cipher.doFinal(cipherBytes);
String decryptedText = new String(decryptedBytes, "UTF8");
System.out.println("Before encryption: " + clearText);
System.out.println("After encryption: " + cipherText);
System.out.println("After decryption: " + decryptedText);
}
}
// Output
/*
Before encryption: I am an Employee
After encryption: }?ス?スj6?スm?スZyc?ス?ス*?ス?スl#l?スdV
After decryption: I am an Employee
*/

Here is the implementation that was mentioned above:
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.StringUtils;
try
{
String passEncrypt = "my password";
byte[] saltEncrypt = "choose a better salt".getBytes();
int iterationsEncrypt = 10000;
SecretKeyFactory factoryKeyEncrypt = SecretKeyFactory
.getInstance("PBKDF2WithHmacSHA1");
SecretKey tmp = factoryKeyEncrypt.generateSecret(new PBEKeySpec(
passEncrypt.toCharArray(), saltEncrypt, iterationsEncrypt,
128));
SecretKeySpec encryptKey = new SecretKeySpec(tmp.getEncoded(),
"AES");
Cipher aesCipherEncrypt = Cipher
.getInstance("AES/ECB/PKCS5Padding");
aesCipherEncrypt.init(Cipher.ENCRYPT_MODE, encryptKey);
// get the bytes
byte[] bytes = StringUtils.getBytesUtf8(toEncodeEncryptString);
// encrypt the bytes
byte[] encryptBytes = aesCipherEncrypt.doFinal(bytes);
// encode 64 the encrypted bytes
String encoded = Base64.encodeBase64URLSafeString(encryptBytes);
System.out.println("e: " + encoded);
// assume some transport happens here
// create a new string, to make sure we are not pointing to the same
// string as the one above
String encodedEncrypted = new String(encoded);
//we recreate the same salt/encrypt as if its a separate system
String passDecrypt = "my password";
byte[] saltDecrypt = "choose a better salt".getBytes();
int iterationsDecrypt = 10000;
SecretKeyFactory factoryKeyDecrypt = SecretKeyFactory
.getInstance("PBKDF2WithHmacSHA1");
SecretKey tmp2 = factoryKeyDecrypt.generateSecret(new PBEKeySpec(passDecrypt
.toCharArray(), saltDecrypt, iterationsDecrypt, 128));
SecretKeySpec decryptKey = new SecretKeySpec(tmp2.getEncoded(), "AES");
Cipher aesCipherDecrypt = Cipher.getInstance("AES/ECB/PKCS5Padding");
aesCipherDecrypt.init(Cipher.DECRYPT_MODE, decryptKey);
//basically we reverse the process we did earlier
// get the bytes from encodedEncrypted string
byte[] e64bytes = StringUtils.getBytesUtf8(encodedEncrypted);
// decode 64, now the bytes should be encrypted
byte[] eBytes = Base64.decodeBase64(e64bytes);
// decrypt the bytes
byte[] cipherDecode = aesCipherDecrypt.doFinal(eBytes);
// to string
String decoded = StringUtils.newStringUtf8(cipherDecode);
System.out.println("d: " + decoded);
}
catch (Exception e)
{
e.printStackTrace();
}

Try this, a simpler solution.
byte[] salt = "ThisIsASecretKey".getBytes();
Key key = new SecretKeySpec(salt, 0, 16, "AES");
Cipher cipher = Cipher.getInstance("AES");

You state that you want to encrypt/decrypt a password. I'm not sure exactly of what your specific use case is but, generally, passwords are not stored in a form where they can be decrypted. General practice is to salt the password and use suitably powerful one-way hash (such as PBKDF2).
Take a look at the following link for more information.
http://crackstation.net/hashing-security.htm

Complete example of encrypting/Decrypting a huge video without throwing Java OutOfMemoryException and using Java SecureRandom for Initialization Vector generation. Also depicted storing key bytes to database and then reconstructing same key from those bytes.
https://stackoverflow.com/a/18892960/185022

Related

How can we do Triple Decryption in java?

I am using a MOL API for VOUCHER recharges. Which returns a PIN number in response is successful. That PIN number will be an encrypted text and I need to triple decrypt it!
I contacted the API support, They provided with the code below:
byte[] PinBytes = Base64.decodeBase64(encryptedText.getBytes("utf-8"));
byte[] VectorBytes = Base64.decodeBase64(vectorKey.getBytes("utf-8"));
byte[] SecretKeyBytes = Base64.decodeBase64(secretKey.getBytes("utf-8"));
TripleDESProvider = CreateTripleDESCryptographicProvider(VectorBytes, SecretKeyBytes)
DecryptedBytes = TripleDESProvider.Decrypt(PinBytes)
Here VectorBytes and SecretKeyBytes are security keys provided by them and PinBytes are the response PIN number which is encrypted.
I googled while I was not able to get a correct solution with these three parameters. Any help, please?
I tried this:
try
{
String encryptedText = "FN0hbSrVzkqhe+w2rQefAQ==";
String vectorKey = "7EsBtzAJjMg=";
//32 bit key
String secretKey = "08061052989102040806105298910204";
byte[] PinBytes = Base64.decodeBase64(encryptedText.getBytes("utf-8"));
byte[] VectorBytes = Base64.decodeBase64(vectorKey.getBytes("utf-8"));
byte[] SecretKeyBytes = Base64.decodeBase64(secretKey.getBytes("utf-8"));
final MessageDigest md = MessageDigest.getInstance("md5");
final byte[] digestOfPassword = md.digest(SecretKeyBytes);
final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
for (int j = 0, k = 16; j < 8;)
{
keyBytes[k++] = keyBytes[j++];
}
final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
final IvParameterSpec iv = new IvParameterSpec(VectorBytes);
final Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
decipher.init(Cipher.DECRYPT_MODE, key, iv);
//final byte[] encData = new sun.misc.BASE64Decoder().decodeBuffer(message);
final byte[] plainText = decipher.doFinal(PinBytes);
System.out.println(plainText.toString());
}
catch (java.security.InvalidAlgorithmParameterException e) { System.out.println("Invalid Algorithm"); }
catch (javax.crypto.NoSuchPaddingException e) { System.out.println("No Such Padding"); }
catch (java.security.NoSuchAlgorithmException e) { System.out.println("No Such Algorithm"); }
catch (java.security.InvalidKeyException e) { System.out.println("Invalid Key"); }
catch (BadPaddingException e) { System.out.println("Invalid Key");}
catch (IllegalBlockSizeException e) { System.out.println("Invalid Key");}
catch (UnsupportedEncodingException e) { System.out.println("Invalid Key");}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Error is Invalid KEY
The document they provide is;
Convert Encrypted Pin into Byte Array from Base64 format
PinBytes = ConvertFromBase64String ("FN0hbSrVzkqhe+w2rQefAQ==")
As Vector Key and Secret Key are provided in Base64 format, thus we need to convert both data into Byte Array as well
VectorBytes = ConvertFromBase64String ("xxxxxxxxx")
SecretKeyBytes = ConvertFromBase64String ("xxxxxxxxxxxx")
Please create your Triple DES Cryptographic Provider and set your IV byte array and Secret Key byte array into your Provider.
TripleDESProvider = CreateTripleDESCryptographicProvider(VectorBytes, SecretKeyBytes)
Please invokes Triple DES Provider decrypt method.
DecryptedBytes = TripleDESProvider.Decrypt(PinBytes)
Finally convert back decrypted bytes back to string.
ConvertToString(DecryptedBytes)
The result should be 8157151550.
I am not sure if this is the right approach but with AES encryption it works. They provided you the vector, use it to initialize the IVParameterSpec, then create Key object and Cipher instance:
// this is the encripted text
byte[] PinBytes = Base64.decodeBase64(encryptedText.getBytes("utf-8"));
byte[] VectorBytes = Base64.decodeBase64(vectorKey.getBytes("utf-8"));
byte[] SecretKeyBytes = Base64.decodeBase64(secretKey.getBytes("utf-8"));
// initialize the vector with the one you receive
IvParameterSpec spec = new IvParameterSpec(VectorBytes);
// create the key. DESede should be correct, but if it doesn't work try also with DES
Key key = new SecretKeySpec(SecretKeyBytes, "DESede");
// Initialize the cipher
Cipher c = Cipher.getInstance("DESede/CBC/PKCS5Padding");
// decrypt the string
c.init(Cipher.DECRYPT_MODE, key, spec);
byte[] decodedDecryptedBytes = c.doFinal(PinBytes);
Base64 object i use is from apache common codec library, but you can use the library you want.
Finally, I Got this answer with same provided secretKey!!
try
{
byte[] PinBytes = Base64.decodeBase64(encryptedText);
byte[] VectorBytes = Base64.decodeBase64(vectorKey);
byte[] SecretKeyBytes = Base64.decodeBase64(secretKey);
// initialize the vector with the one you receive
IvParameterSpec spec = new IvParameterSpec(VectorBytes);
// create the key. DESede should be correct, but if it doesn't work try also with DES
Key key = new SecretKeySpec(SecretKeyBytes, "DESede");
// Initialize the cipher
Cipher c = Cipher.getInstance("DESede/CBC/PKCS5Padding");
// decrypt the string
c.init(Cipher.DECRYPT_MODE, key, spec);
byte[] decodedDecryptedBytes = c.doFinal(PinBytes);
return new String(decodedDecryptedBytes, "UTF-8");
}
catch (java.security.InvalidAlgorithmParameterException e) { System.out.println("Invalid Algorithm"); }
catch (javax.crypto.NoSuchPaddingException e) { System.out.println("No Such Padding"); }
catch (java.security.NoSuchAlgorithmException e) { System.out.println("No Such Algorithm"); }
catch (java.security.InvalidKeyException e) { System.out.println("InvalidKeyException : Invalid Key"); }
catch (BadPaddingException e) { System.out.println("BadPaddingException : Invalid Key");}
catch (IllegalBlockSizeException e) { System.out.println("IllegalBlockSizeException : Invalid Key");}
catch (UnsupportedEncodingException e) { System.out.println("UnsupportedEncodingException : Invalid Key");}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
The Mistake was doing this:
byte[] SecretKeyBytes = Base64.decodeBase64(secretKey.getBytes("utf-8"));
I don't know why this happens! But by removing that I got the answer!!

Decrypt a string with DES in PHP that's been encrypted by Java

I've been banging my head against the wall trying to figure out exactly how to format everything to decrypt this string in PHP that's been encrypted in a custom Java class.
Here's the relevent functions from the Java class. The "salt" variable is a class variable byte array set earlier:
public DesEncrypter(String passPhrase) {
try {
// Create the key
KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt,
iterationCount);
SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES")
.generateSecret(keySpec);
ecipher = Cipher.getInstance(key.getAlgorithm());
dcipher = Cipher.getInstance(key.getAlgorithm());
// Prepare the parameter to the ciphers
AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt,
iterationCount);
// Create the ciphers
ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
} catch (java.security.InvalidAlgorithmParameterException e) {
} catch (java.security.spec.InvalidKeySpecException e) {
} catch (javax.crypto.NoSuchPaddingException e) {
} catch (java.security.NoSuchAlgorithmException e) {
} catch (java.security.InvalidKeyException e) {
}
}
public String encrypt(String str) {
try {
// Encode the string into bytes using utf-8
byte[] utf8 = str.getBytes("UTF8");
// Encrypt
byte[] enc = ecipher.doFinal(utf8);
// Encode bytes to base64 to get a string
return new sun.misc.BASE64Encoder().encode(enc);
} catch (javax.crypto.BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
}
return null;
}
public String decrypt(String str) {
try {
// Decode base64 to get bytes
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
// Decrypt
byte[] utf8 = dcipher.doFinal(dec);
// Decode using utf-8
return new String(utf8, "UTF8");
} catch( Exception ex) {
ex.printStackTrace(System.err);
}
return null;
}
And here's what I have so far in PHP (FYI, I'm using this encryption library in PHP https://github.com/phpseclib/phpseclib):
$app->get('/decrypt', function () use ($app) {
$data = '3aCRLRd3srA/QF4MQb0D+P==';
$salt = pack('nvc*', 0xB7, 0x9A, 0xC1, 0x34, 0x26, 0x89, 0xW3, 0x30);
$secret = "secret";
$keyLength = 16;
$cipher = new Crypt_DES(CRYPT_DES_MODE_CBC);
$cipher->setPassword($secret, 'pbkdf2', 'md5', $salt, $keyLength);
var_dump($cipher->decrypt($data));
});
Right now it's dumping out a bunch of binary, which I've tried base64_decoding, but that doesn't do anything either.
If key.getAlgorithm() is "DES" then you need to provide a fully specified Cipher name like "DES/CBC/PKCS5Padding".
You will also need to provide the IV if it is non-null. Usually the IV is prepended to the ciphertext.
You can get the IV with cipher.getIV() and set with $cipher->setIV('...');.

Generating and using two keys for encryption and decryption in Java

I am working on a Java application which requires I use two keys
generated from different Strings for encrypting and decrypting. One
String is coming from user and other is master key. I looked on net
and found a few references regarding it. I would really like some
help in knowing how to implement this. I will show what I have now.
So as you can see from code, I used some code from other stackoverflow post and modified it a bit. I just don't know how to generate the 2 keys from 2 Strings and from where I can get the SecretKey desKey used for decryption.
Code :
public class Encryption {
public void doStuff() {
String plaintext = "abc";
SecretKey k1 = generateDESkey();
SecretKey k2 = generateDESkey();
String firstEncryption = desEncryption(plaintext, k1);
String decryption = desDecryption(firstEncryption, k2);
String secondEncryption = desEncryption(decryption, k1);
System.out.println(firstEncryption);
System.out.println(decryption);
System.out.println(secondEncryption);
}
public static SecretKey generateDESkey() {
KeyGenerator keyGen = null;
try {
keyGen = KeyGenerator.getInstance("DESede");
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(Test.class
.getName()).log(Level.SEVERE, null, ex);
}
try {
assert keyGen != null;
keyGen.init(112); // key length 56
return keyGen.generateKey();
} catch (NullPointerException ex){
return null;
}
}
public static String desEncryption(String strToEncrypt, SecretKey desKey) {
try {
Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, desKey);
return Base64.encode(cipher.doFinal(strToEncrypt.getBytes()));
} catch (NoSuchAlgorithmException | NoSuchPaddingException |
IllegalBlockSizeException | BadPaddingException |
InvalidKeyException ex) {
Logger.getLogger(Test.class
.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
public static String desDecryption(String strToDecrypt, SecretKey desKey) {
try {
Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, desKey);
return new String(cipher.doFinal(Base64.decode(strToDecrypt)));
} catch (NoSuchAlgorithmException | BadPaddingException | IllegalBlockSizeException
| InvalidKeyException | NoSuchPaddingException ex) {
Logger.getLogger(Test.class
.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
}
If there is any confusion or doubts about it. Kindly let me know.
Answer for the code before it was changed.
You're trying to do DESede with only two keys instead of three.
That might generally work, but not as you've written. The problem is the padding. In the second step, you try to decrypt the ciphertext with an other key than with what it was encrypted, so the decryption will fail more than 255 out of 256 times, because the padding will be wrong (also because you use Base64 encoding where it is not necessary).
If you really want to do it, you will have to decrypt without padding and without Base64 encoding. The good thing is that the unencoded ciphertext is already a multiple of the blocksize, so there is no stopping you to use "DES/ECB/NoPadding".
public static void main(String[] args) {
// First I would like to create keys by giving Strings
SecretKey k1 = generateDESkey();
SecretKey k2 = generateDESkey();
// encryption
byte[] firstEncryption = desEncryption("plaintext".getBytes("UTF-8"), k1, false);
byte[] decryption = desDecryption(firstEncryption, k2, true);
byte[] secondEncryption = desEncryption(decryption, k1, true);
// decryption
byte[] firstDecryption = desDecryption(secondEncryption, k1, true);
byte[] encryption = desEncryption(firstDecryption, k2, true);
byte[] secondDecryption = desDecryption(encryption, k1, false);
System.out.println(new String(secondDecryption)); // plaintext
}
public static byte[] desEncryption(byte[] strToEncrypt, SecretKey desKey, boolean noPadding) {
try {
Cipher cipher = Cipher.getInstance(noPadding ? "DES/ECB/NoPadding" : "DES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, desKey);
return cipher.doFinal(strToEncrypt);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static byte[] desDecryption(byte[] strToDecrypt, SecretKey desKey, boolean noPadding) {
try {
Cipher cipher = Cipher.getInstance(noPadding ? "DES/ECB/NoPadding" : "DES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, desKey);
return cipher.doFinal(strToDecrypt);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
This is actually an equivalent implementation of DESede with two keys when the general key is constructed in this way:
SecretKey k1 = generateDESkey();
SecretKey k2 = generateDESkey();
byte[] edeKeyBytes = new byte[24];
System.arraycopy(k1.getEncoded(), 0, edeKeyBytes, 0, 8);
System.arraycopy(k2.getEncoded(), 0, edeKeyBytes, 8, 8);
System.arraycopy(k1.getEncoded(), 0, edeKeyBytes, 16, 8);
edeKey = new SecretKeySpec(edeKeyBytes, "DESede");
Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, edeKey);
System.out.println(Base64.encode(cipher.doFinal("plaintext".getBytes("UTF-8"))));
DESede uses three keys which we will call k1, k2 and k3. All of them are concatenated into a single byte array. In your case k1 is used a second time in place of k3.

Java Decryption

I have a problem with with
javax.crypto.Cipher
When I write this lines of code
Cipher cipher;
byte[] bytes = null;
try
{
cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, generateAESKey128b(key));
bytes = cipher.doFinal(input.getBytes("UTF-8"));
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
catch (NoSuchPaddingException e)
{
e.printStackTrace();
}
catch (InvalidKeyException e)
{
e.printStackTrace();
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
catch (IllegalBlockSizeException e)
{
e.printStackTrace();
}
catch (BadPaddingException e)
{
e.printStackTrace();
}
The console give me this error
javax.crypto.IllegalBlockSizeException
Input length must be multiple of 16 when
decrypting with padded cipher
at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
at com.sun.crypto.provider.AESCipher.engineDoFinal(DashoA13*..)
at javax.crypto.Cipher.doFinal(DashoA13*..)
at it.unitn.se.gym.backend.utils.Security.AES128Decode(Security.java:109)
at it.unitn.se.gym.backend.utils.Security.decode_AES128_Base64(Security.java:96)
at it.unitn.se.gym.backend.WebService.main(WebService.java:42)
Exception in thread "main" java.lang.NullPointerException
at it.unitn.se.gym.backend.utils.Security.decode_AES128_Base64(Security.java:97)
at it.unitn.se.gym.backend.WebService.main(WebService.java:42)
The first 2 lines of code are correct but when I pass the attribute "text", of type byte[], to the doFinal function, it give me the error.
Can someone tell me why?
SOLVED:
Okay, problem solved
byte[] encrypted = UniversalBase64Encoder.decode(input);
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, generateAESKey128b(key));
byte[] originalBytes = cipher.doFinal(encrypted);
This is the right code that I wrote
The problem is that you're trying to decrypt a string that was not encrypted, and in doing so are violating an assumption of the decryption algorithm (that its input size is always a multiple of 16).
Here's a block of code that encrypts and then decrypts a string. Notice that when the encrypted string is printed, it's 16 bytes long, even though the input string is not. The encryption algorithm pads the input string out to make it a multiple of 16 bytes before encrypting it. That 16-byte-long encrypted string is now a valid input for decryption.
This assumption (that the result of encrypting will be an even size) is quite standard. It not only makes the decryption/encryption algorithm easier to write, but it also prevents an attacker from knowing the length of the thing you encrypted.
byte[] keyBytes = new byte[16];
keyBytes[0] = 1;
SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
String input = "hello";
Cipher cipher;
byte[] bytes = null;
cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, key);
bytes = cipher.doFinal(input.getBytes("UTF-8"));
System.out.println("Encoded: "+Arrays.toString(bytes));
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decoded = cipher.doFinal(bytes);
System.out.println("Decoded: "+new String(decoded, "UTF-8"));

Missing argument while converting RijndaelManaged in java

while converting a .net code of decryption to java I got an exception
Exception in thread "main" java.lang.IllegalArgumentException: Missing argument
at javax.crypto.spec.SecretKeySpec.<init>(DashoA13*..)
at com.motorola.gst.DecryptTest3.Decrypt(DecryptTest3.java:90)
at com.motorola.gst.DecryptTest3.main(DecryptTest3.java:36)
well I'm trying it for the first time both decryption and converting a .net code to java
here is the .net code that I'm trying to convert
private static string Decrypt(string encryptedText, string completeEncodedKey, int keySize)
{
RijndaelManaged aesEncryption = new RijndaelManaged();
aesEncryption.KeySize = keySize;
aesEncryption.BlockSize = 128;
aesEncryption.Mode = CipherMode.CBC;
aesEncryption.Padding = PaddingMode.PKCS7;
aesEncryption.IV = Convert.FromBase64String(ASCIIEncoding.UTF8.GetString(Convert.FromBase64String(completeEncodedKey)).Split(',')[0]);
aesEncryption.Key = Convert.FromBase64String(ASCIIEncoding.UTF8.GetString(Convert.FromBase64String(completeEncodedKey)).Split(',')[1]);
ICryptoTransform decrypto = aesEncryption.CreateDecryptor();
byte[] encryptedBytes = Convert.FromBase64CharArray(encryptedText.ToCharArray(), 0, encryptedText.Length);
return ASCIIEncoding.UTF8.GetString(decrypto.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length));
}
I went through many posts and found Decrypting bytes encrypted by .NET's RijndaelManaged using Java is more related to my case.
I followed these and wrote my decrypt function as ::
private static String Decrypt(String encryptedText, String completeEncodedKey,int keySize) {
//get completeEncodedKey in bytes and then to string
String decodedcompleteEncodedKey = StringUtils.newStringUtf8(Base64.decodeBase64(completeEncodedKey));
System.out.println("Decoded completeEncodedKey Key :: "+decodedcompleteEncodedKey);
int indexComma = decodedcompleteEncodedKey.indexOf(',');
System.out.println("COmma Index :: "+indexComma);
String IV = decodedcompleteEncodedKey.substring(0, indexComma);
String Key = decodedcompleteEncodedKey.substring(indexComma+1,decodedcompleteEncodedKey.length());
System.out.println("IV::: "+IV);
System.out.println("Key::: "+Key);
byte[] sessionKey = null;
byte[] iv = null ;
byte[] plaintext = encryptedText.getBytes();
Cipher cipher = null;
try {
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(sessionKey, "AES"), new IvParameterSpec(iv));
byte[] ciphertext = cipher.doFinal(plaintext);
} catch (IllegalBlockSizeException e) {
System.out.println("IllegalBlockSizeException");
e.printStackTrace();
} catch (BadPaddingException e) {
System.out.println("BadPaddingException");
e.printStackTrace();
} catch (InvalidKeyException e) {
System.out.println("InvalidKeyException");
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
System.out.println("InvalidAlgorithmParameterException");
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
System.out.println("NoSuchAlgorithmException");
e.printStackTrace();
} catch (NoSuchPaddingException e) {
System.out.println("NoSuchPaddingException");
e.printStackTrace();
}
return null;
}
but now I'm getting Exception in thread "main" java.lang.IllegalArgumentException: Missing argument.
can anyone help me getting these errors fixed.
any help would be appreciated.
thanks!!
For me the problem was calling new SecretKeySpec(sessionKey, "AES") with sessionKey = null.

Categories

Resources