Weird String format when decrypting - java

I am trying to program a little challenge response app. My idea is to enter a text, encrypt it, show it as a QR code so the other side can scan it, decrypt it and show me the original text. But the final text is in a strange format and i can't figure out whats wrong. Here is what I am doing right now:
The 'challenge' string is the text from a TextView
byte[] secret = encrypt(publicKey, challenge.getBytes(StandardCharsets.UTF_8));
challengeenc = bytes2String(secret);
public byte[] encrypt(PublicKey key, byte[] plaintext) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException
{
Cipher enc = Cipher.getInstance("RSA");
enc.init(Cipher.ENCRYPT_MODE, key);
return enc.doFinal(plaintext);
}
private static String bytes2String(byte[] bytes)
{
StringBuilder string = new StringBuilder();
for (byte b : bytes) {
String hexString = Integer.toHexString(0x00FF & b);
string.append(hexString.length() == 1 ? "0" + hexString : hexString);
}
return string.toString();
}
Then the QR code part comes to transform and read it, but this also has to work since the challengeenc is equal to the string I read with the QR code scanner (challenge)
byte[] loesung = decrypt(privateKey, challenge.getBytes());
loesungstr = bytes2String(loesung);
Now the loesungstr should be equal to the string I started with but right now I entered "aaaaaaaa" and the loesungstr is: "1a3e3aa2e6a804fe6035c3f2879219ff971f119dee7e513f9311a27c3e7a7d58a27f826c45c5ace3699bc11ce7176a1ee3c9f4c1190402af5a79bbd8944750c85e73e4cda459ff904156186e1c010ea861a8f0be78594c00e22d049213b381de8afd877877ae9cf59169c77f088fe552a0e552260ed68f599858eaf1585916128778758db5c6d8efe32844d208932289f86202c10485533cdd89f1bd08d6e86f81c201d7d707ba435a5472a36cd7dc7584156000004b4a7a8fa320d3f3a919f9f901d86b965ba09a452372fd35cf84fc3a1841c18196c735c76b2ce75bf8bd03a671d42f6c0bac39eabf56ea09b37d00176f1b45a3917f81226ef2f0a312e515"
I tried a lot of stuff and converted this string from hex to string, from hex to ASCII, ... but I am not able to figure out where it went wrong..
Does somebody have an idea what this string might be?
PS: Since I can sign a text and verify the signature I know the key pair I created is correct

Your code should follow this basic pattern, which I just tested successfully.
In particular, make sure that every variable has a good name. Maybe this is where your confusion comes from.
import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
public class Rsa {
static KeyPair generateKeyPair() throws GeneralSecurityException {
KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
gen.initialize(4096);
return gen.generateKeyPair();
}
static byte[] encrypt(byte[] plaintext, PublicKey key) throws GeneralSecurityException {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, key);
return cipher.doFinal(plaintext);
}
static byte[] decrypt(byte[] ciphertext, PrivateKey key) throws GeneralSecurityException {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, key);
return cipher.doFinal(ciphertext);
}
public static void main(String[] args) throws GeneralSecurityException {
KeyPair keys = generateKeyPair();
byte[] plaintext = "hello, world".getBytes(StandardCharsets.UTF_8);
byte[] ciphertext = encrypt(plaintext, keys.getPublic());
byte[] plainAgain = decrypt(ciphertext, keys.getPrivate());
System.out.println(new String(plainAgain, StandardCharsets.UTF_8));
}
}

you should have another method that decode the encoded string, i.e hexStringToByteArray() before decrypting it:
this method is from this answer:
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
return data;
}
and you use it when decrypting as below:
byte[] loesung = decrypt(privateKey, hexStringToByteArray(challenge));
to get the original plain text:
String plaintext = new String(loesung);

Related

Encryption and Decryption with PBKDF2 and AES256 - practical example needed - how do I get the Derived key

I am trying to understand how a derived key is obtained by using PBKDF2, with SHA256.
I am getting tangled up, and need a clear, easy to understand example.
What I have so far:
I have found https://en.wikipedia.org/wiki/PBKDF2 which has a an example, but with SHA1, with the following values:
PASSWORD plnlrtfpijpuhqylxbgqiiyipieyxvfsavzgxbbcfusqkozwpngsyejqlmjsytrmd UTF8
SALT A009C1A485912C6AE630D3E744240B04 HEX
Hashing function SHA1
Key Size 128
Iterations 1000
I have been using https://gchq.github.io/CyberChef and can get the output 17EB4014C8C461C300E9B61518B9A18B which matches the derived key bytes in the Wikipedia example.
I have been working with https://mkyong.com/java/java-aes-encryption-and-decryption/ which has a method named getAESKeyFromPassword, which is here:
// Password derived AES 256 bits secret key
public static SecretKey getAESKeyFromPassword(char[] password, byte[] salt)
throws NoSuchAlgorithmException, InvalidKeySpecException {
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
// iterationCount = 65536
// keyLength = 256
KeySpec spec = new PBEKeySpec(password, salt, 65536, 256);
SecretKey secret = new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES");
return secret;
}
I want to carry out the same "investigation", as I have done with the Wikipedia page, SHA1, and CyberChef, but using SHA256 (replacing the values in the Java code, to match the salt, password, iterations, from the example).
This is where my confusion starts:
If I were to use CyberChef to work on the same values as above, but replace with SHA256:
PASSWORD plnlrtfpijpuhqylxbgqiiyipieyxvfsavzgxbbcfusqkozwpngsyejqlmjsytrmd UTF8
SALT A009C1A485912C6AE630D3E744240B04 HEX
Hashing function SHA256
Key Size 128
Iterations 1000
I would expect the derived key to be the same in CyberChef, as the https://mkyong.com/java/java-aes-encryption-and-decryption/ example.
It's not.
I cannot help but think there is a flaw in my understanding.
Can someone please provide a simple (worked-through) example of PBKDF2 with SHA256, so I can understand what is going on. If the derived key is not meant to be the same (as with the SHA1 example, please explain why).
Is the Java SecretKey:
SecretKey secret = new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES");
The same as the derived key?
There seems to be a lack of easy-to-understand examples to follow.
Thanks
Miles.
Thank you all for your input, especially Topaco :)
I am going to answer my question, as I have spent some time working on a MCVE, and have managed to get the same SecretKey as cyberChef.
The secret key value is: 28869b5f31ae29236f164c5cb33e2e3bb46f483867a15f8e7208e1836070f64a
Here is the output from cyberChef:
Here is the Java code, and output from running it:
package crypto;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.util.Base64;
public class EncryptDecryptAesGcmPassword {
private static final String ENCRYPT_ALGO = "AES/GCM/NoPadding";
private static final int TAG_LENGTH_BIT = 128; // must be one of {128, 120, 112, 104, 96}
private static final int IV_LENGTH_BYTE = 12;
private static final int SALT_LENGTH_BYTE = 16;
public static final int ITERATION_COUNT = 1000;
public static final int KEY_LENGTH = 256;
private static final Charset UTF_8 = StandardCharsets.UTF_8;
// return a base64 encoded AES encrypted text
public static String encrypt(byte[] salt, byte[] pText, String password) throws Exception {
// GCM recommended 12 bytes iv?
byte[] iv = getRandomNonce(IV_LENGTH_BYTE);
// secret key from password
SecretKey aesKeyFromPassword = getAESKeyFromPassword(password.toCharArray(), salt);
Cipher cipher = Cipher.getInstance(ENCRYPT_ALGO);
// ASE-GCM needs GCMParameterSpec
cipher.init(Cipher.ENCRYPT_MODE, aesKeyFromPassword, new GCMParameterSpec(TAG_LENGTH_BIT, iv));
byte[] cipherText = cipher.doFinal(pText);
// prefix IV and Salt to cipher text
byte[] cipherTextWithIvSalt = ByteBuffer.allocate(iv.length + salt.length + cipherText.length)
.put(iv)
.put(salt)
.put(cipherText)
.array();
// string representation, base64, send this string to other for decryption.
return Base64.getEncoder().encodeToString(cipherTextWithIvSalt);
}
// we need the same password, salt and iv to decrypt it
private static String decrypt(String cText, String password) throws Exception {
byte[] decode = Base64.getDecoder().decode(cText.getBytes(UTF_8));
// get back the iv and salt from the cipher text
ByteBuffer bb = ByteBuffer.wrap(decode);
byte[] iv = new byte[IV_LENGTH_BYTE];
bb.get(iv);
byte[] salt = new byte[SALT_LENGTH_BYTE];
bb.get(salt);
byte[] cipherText = new byte[bb.remaining()];
bb.get(cipherText);
// get back the aes key from the same password and salt
SecretKey aesKeyFromPassword = getAESKeyFromPassword(password.toCharArray(), salt);
Cipher cipher = Cipher.getInstance(ENCRYPT_ALGO);
cipher.init(Cipher.DECRYPT_MODE, aesKeyFromPassword, new GCMParameterSpec(TAG_LENGTH_BIT, iv));
byte[] plainText = cipher.doFinal(cipherText);
return new String(plainText, UTF_8);
}
public static byte hexToByte(String hexString) {
int firstDigit = toDigit(hexString.charAt(0));
int secondDigit = toDigit(hexString.charAt(1));
return (byte) ((firstDigit << 4) + secondDigit);
}
public static byte[] decodeHexString(String hexString) {
if (hexString.length() % 2 == 1) {
throw new IllegalArgumentException(
"Invalid hexadecimal String supplied.");
}
byte[] bytes = new byte[hexString.length() / 2];
for (int i = 0; i < hexString.length(); i += 2) {
bytes[i / 2] = hexToByte(hexString.substring(i, i + 2));
}
return bytes;
}
private static int toDigit(char hexChar) {
int digit = Character.digit(hexChar, 16);
if (digit == -1) {
throw new IllegalArgumentException(
"Invalid Hexadecimal Character: "+ hexChar);
}
return digit;
}
// Random byte[] with length numBytes
public static byte[] getRandomNonce(int numBytes) {
byte[] nonce = new byte[numBytes];
new SecureRandom().nextBytes(nonce);
return nonce;
}
// Password derived AES 256 bits secret key
public static SecretKey getAESKeyFromPassword(char[] password, byte[] salt)
throws NoSuchAlgorithmException, InvalidKeySpecException {
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
// iterationCount = 1000
// keyLength = 256
KeySpec spec = new PBEKeySpec(password, salt, ITERATION_COUNT,
KEY_LENGTH);
SecretKey secret = new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES");
String encodedKey = hex(secret.getEncoded());
// print SecretKey as hex
System.out.println("SecretKey: " + encodedKey);
return secret;
}
// hex representation
public static String hex(byte[] bytes) {
StringBuilder result = new StringBuilder();
for (byte b : bytes) {
result.append(String.format("%02x", b));
}
return result.toString();
}
public static void main(String[] args) throws Exception {
String OUTPUT_FORMAT = "%-30s:%s";
String PASSWORD = "plnlrtfpijpuhqylxbgqiiyipieyxvfsavzgxbbcfusqkozwpngsyejqlmjsytrmd";
// plain text
String pText = "AES-GSM Password-Bases encryption!";
// convert hex string to byte[]
byte[] salt = decodeHexString("A009C1A485912C6AE630D3E744240B04");
String encryptedTextBase64 = EncryptDecryptAesGcmPassword.encrypt(salt, pText.getBytes(UTF_8), PASSWORD);
System.out.println("\n------ AES GCM Password-based Encryption ------");
System.out.println(String.format(OUTPUT_FORMAT, "Input (plain text)", pText));
System.out.println(String.format(OUTPUT_FORMAT, "Encrypted (base64) ", encryptedTextBase64));
System.out.println("\n------ AES GCM Password-based Decryption ------");
System.out.println(String.format(OUTPUT_FORMAT, "Input (base64)", encryptedTextBase64));
String decryptedText = EncryptDecryptAesGcmPassword.decrypt(encryptedTextBase64, PASSWORD);
System.out.println(String.format(OUTPUT_FORMAT, "Decrypted (plain text)", decryptedText));
}
}
Running this code, produces the following:
SecretKey: 28869b5f31ae29236f164c5cb33e2e3bb46f483867a15f8e7208e1836070f64a
------ AES GCM Password-based Encryption ------
Input (plain text) :AES-GSM Password-Bases encryption!
Encrypted (base64) :/PuTLBTKVWgJB2iMoAnBpIWRLGrmMNPnRCQLBABOkwNeY8BrrdtoRNVFqZ+xmUjvF2PET6Ne2+PAp34QLCUFjQodTMdmzaNAfzcLWOf4
------ AES GCM Password-based Decryption ------
Input (base64) :/PuTLBTKVWgJB2iMoAnBpIWRLGrmMNPnRCQLBABOkwNeY8BrrdtoRNVFqZ+xmUjvF2PET6Ne2+PAp34QLCUFjQodTMdmzaNAfzcLWOf4
SecretKey: 28869b5f31ae29236f164c5cb33e2e3bb46f483867a15f8e7208e1836070f64a
Decrypted (plain text) :AES-GSM Password-Bases encryption!
Thanks
Miles.

AES Encryption key generation that is consistent each execution?

I found this well written example of how to use AES encryption, and I will admit some of the more advanced aspects are beyond me. The class works fine, provided I'm using the same instance object. If I create another object, using the same exact passPhrase - that object can no longer properly decode any kind of string or data that the previous object created. I can only conclude that since this code takes the rather weak passPhrase string, mixes SALT, and builds a stronger 128-bit key - that this process of key construction is somehow randomized each time around. The significance being:
new AESEncrypter("MyPassword") <> new AESEncrypter("MyPassword")
Could someone help me modify the class below to get the desired behavior:
AESEncrypter a = new AESEncrypter("MyPassword")
String encoded = a.encrypt("my message")
AESEncrypter b = new AESEncrypter("MyPassword")
b.decrypt(encoded) == "my message"
import java.security.spec.KeySpec;
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 sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class AESEncrypter {
private static final byte[] SALT = {
(byte) 0xA9, (byte) 0x9B, (byte) 0xC8, (byte) 0x32,
(byte) 0x56, (byte) 0x35, (byte) 0xE3, (byte) 0x03
};
private static final int ITERATION_COUNT = 65536;
private static final int KEY_LENGTH = 128;
public Cipher ecipher;
public Cipher dcipher;
AESEncrypter(String passPhrase) throws Exception {
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec spec = new PBEKeySpec(passPhrase.toCharArray(), SALT, ITERATION_COUNT, KEY_LENGTH);
SecretKey tmp = factory.generateSecret(spec);
// I Think the problem is here???
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
ecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
ecipher.init(Cipher.ENCRYPT_MODE, secret);
dcipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] iv = ecipher.getParameters().getParameterSpec(IvParameterSpec.class).getIV();
dcipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));
}
public String encrypt(String encrypt) throws Exception {
byte[] bytes = encrypt.getBytes("UTF8");
byte[] encrypted = encrypt(bytes);
return new BASE64Encoder().encode(encrypted);
}
public byte[] encrypt(byte[] plain) throws Exception {
return ecipher.doFinal(plain);
}
public String decrypt(String encrypt) throws Exception {
byte[] bytes = new BASE64Decoder().decodeBuffer(encrypt);
byte[] decrypted = decrypt(bytes);
return new String(decrypted, "UTF8");
}
public byte[] decrypt(byte[] encrypt) throws Exception {
return dcipher.doFinal(encrypt);
}
public static void main(String[] args) throws Exception {
String message = "MESSAGE";
String password = "PASSWORD";
AESEncrypter encrypter1 = new AESEncrypter(password);
AESEncrypter encrypter2 = new AESEncrypter(password);
String encrypted1 = encrypter1.encrypt(message);
String encrypted2 = encrypter2.encrypt(message);
System.out.println("Display Encrypted from object 1 and 2..why do they differ?" );
System.out.println(encrypted1) ;
System.out.println(encrypted2) ;
System.out.println("Display Each object decrypting its own encrypted msg. Works as expected" );
System.out.println(encrypter1.decrypt(encrypted1)) ;
System.out.println(encrypter2.decrypt(encrypted2)) ;
System.out.println("Attempt to decrypt the each others msg.. will fail" );
System.out.println(encrypter1.decrypt(encrypted2)) ;
System.out.println(encrypter2.decrypt(encrypted1)) ;
}
}
Display Encrypted from object 1 and 2..why do they differ?
drGy+BNSHPy34NWkkcNqLQ==
9p06VfBgTuh7TizZSbvKjw==
Display Each object decrypting its own encrypted msg. Works as expected
MESSAGE
MESSAGE
Attempt to decrypt the each others msg.. will fail
Error:
Exception in thread "main" javax.crypto.BadPaddingException: Given final block not properly padded
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:966)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:824)
at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:436)
at javax.crypto.Cipher.doFinal(Cipher.java:2165)
The problem is that when you initialize a new Cipher in CBC mode, it generates a fresh and random IV for you. This Initialization Vector doesn't have to be secret, but it has to be unpredictable to provide semantic security. You can simply put the IV in front of the ciphertext and use it for decryption.
public byte[] encrypt(byte[] plain) throws Exception {
byte[] iv = ecipher.getParameters().getParameterSpec(IvParameterSpec.class).getIV();
byte[] ct = ecipher.doFinal(plain);
byte[] result = new byte[ct.length + iv.length];
System.arraycopy(iv, 0, result, 0, iv.length);
System.arraycopy(ct, 0, result, iv.length, ct.length);
return result;
}
public byte[] decrypt(byte[] encrypt) throws Exception {
byte[] iv = new byte[dcipher.getBlockSize()];
byte[] ct = new byte[encrypt.length - dcipher.getBlockSize()];
System.arraycopy(encrypt, 0, iv, 0, dcipher.getBlockSize());
System.arraycopy(encrypt, dcipher.getBlockSize(), ct, 0, ct.length);
dcipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));
return dcipher.doFinal(ct);
}
You will need to store secret during the initialization step in a private variable for the decryption to work.
Keep in mind that the salt for PBDKF2 should also be random and 16 bytes long. You can store it alongside of the IV.

encrypting with AES CBC Java

I have little problem. When I try to encrypt text and then decrypt this text I get an error:
javax.crypto.IllegalBlockSizeException: Input length must be multiple
of 16 when decrypting with padded cipher
Here is my code:
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.InvalidAlgorithmParameterException;
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.ShortBufferException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
/**
*
* #author Grzesiek
*/
public class SymmethricCipherCBC {
/* Klucz: */
private byte[] keyBytes = new byte[] {
0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,
0x00,0x01,0x02,0x03,0x04,0x05
};
/* Wektor inicjalizacyjny: */
private byte[] ivBytes = new byte[] {
0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,
0x00,0x01,0x02,0x03,0x04,0x05
};
private Cipher cipher;
private SecretKeySpec keySpec;
private IvParameterSpec ivSpec;
public SymmethricCipherCBC() throws NoSuchAlgorithmException, NoSuchPaddingException{
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); //Utworzenie obiektu dla operacji szyfrowania/deszyfrowania algorytmem AES w trybie CBC.
keySpec = new SecretKeySpec(keyBytes, "AES"); // Utworzenie obiektu klucza dla algorytmu AES z tablicy bajtow
ivSpec = new IvParameterSpec(ivBytes); // // Utworzenie obiektu dla wektora inicjalizacyjnego
}
public String encryptText(String plainText) throws NoSuchAlgorithmException,
InvalidKeyException,
NoSuchPaddingException,
InvalidAlgorithmParameterException,
ShortBufferException,
IllegalBlockSizeException,
BadPaddingException,
UnsupportedEncodingException{
int cipherTextLength;
byte[] cipherText; // Bufor dla szyfrogramu
byte[] plainTextBytes = plainText.getBytes(); // Reprezentacja tekstu jawnego w bajtach
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec); //Inicjalizacja obiektu dla operacji szyfrowania z kluczem okreslonym przez keySpec:
cipherText = new byte[cipher.getOutputSize(plainTextBytes.length)]; //Utworzenie buforu dla szyfrogramu
cipherTextLength = cipher.update(plainTextBytes, 0, plainTextBytes.length, cipherText, 0); // Szyfrowanie tekstu jawnego
cipherTextLength += cipher.doFinal(cipherText, cipherTextLength); //Zakonczenie szyfrowania
return new BigInteger(1, cipherText).toString(16); // zapisanie 16
}
public String decryptText(String ciptherTextString) throws InvalidKeyException, InvalidAlgorithmParameterException, ShortBufferException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException{
byte[] cipherTextBytes = ciptherTextString.getBytes();
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec); //Inicjalizacja obiektu cipher dla odszyfrowywania z kluczem okreslonym przez keySpec
byte[] plainTextBytes = new byte[cipher.getOutputSize(cipherTextBytes.length)]; // Utworzenie wyzerowanej tablicy
int plainTextLength = cipher.update(cipherTextBytes, 0, cipherTextBytes.length, plainTextBytes, 0);
plainTextLength += cipher.doFinal(plainTextBytes, plainTextLength);
return new String(plainTextBytes); //Odtworzona wiadomosc
}
}
Any ideas what I should do?
You're doing it harder than necessary, and you're encrypting your cipher text when doing
cipher.doFinal(cipherText, cipherTextLength);
I would rewrite it as is:
public String encryptText(String plainText) throws ... {
byte[] plainTextBytes = plainText.getBytes("UTF8");
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
byte[] encrypted = cipher.doFinal(plainTextBytes);
return toHex(encrypted);
}
public String decryptText(String cipherTextString) throws ... {
byte[] cipherTextBytes = fromHex(cipherTextString);
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
byte[] plainTextBytes = cipher.doFinal(cipherTextBytes);
return new String(plainTextBytes, "UTF8");
}
as far as I can tell, you are taking the byte array output from the encryption algorithm, and converting it to a hex string using BigInteger. then the decryption algorithm takes the hex string and converts it to the byte representation of the ASCII characters in the hex string using .toString()
This is where your code is wrong (among other places). rather than turning, say, the hex string output "FFFF" into a byte array [0xff, 0xff] it turns it into the byte array [0x46,0x46,0x46,0x46] (e.g. the ASCII byte representation of the upper case F). This means that not only will all of the bytes in your conversion be wrong, the byte array will be the wrong length (which causes the exception you listed in your question).
Instead, you should return byte[] from your encryption method, and accept byte[] as a parameter in your decryption method. failing that, you should use something like Apache Commons Codec's Hex class to reliably convert between byte arrays and hex strings.

Why doesn't this simple AES encryption work?

Why does not this AES encryption work? I've written it in Java to test, but I am not able to decrypt. I get garbage upon decryption. Why? Its so simple - In the main method, print plain text, encrypt, print cipher text, decrypt, print plain text again. Am I doing something wrong? Please help me figure out the problem.
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class AESTest {
public static void main(String [] args) {
try {
String plainText = "Hello World!!!!!";
String encryptionKey = "E072EDF9534053A0B6C581C58FBF25CC";
System.out.println("Before encryption - " + plainText);
String cipherText = encrypt(plainText, encryptionKey);
System.out.println("After encryption - " + cipherText);
String decrypted = decrypt(cipherText, encryptionKey);
System.out.println("After decryption - " + decrypted);
} catch (Exception e) {
e.printStackTrace();
}
}
public static String encrypt(String plainText, String passkey) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding", "SunJCE");
SecretKeySpec key = new SecretKeySpec(hexStringToByteArray(passkey), "AES");
cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(new byte[cipher.getBlockSize()]));
String cipherText = new String(cipher.doFinal(plainText.getBytes()));
return cipherText;
}
public static String decrypt(String cipherText, String passkey) throws Exception{
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding", "SunJCE");
SecretKeySpec key = new SecretKeySpec(hexStringToByteArray(passkey), "AES");
cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(new byte[cipher.getBlockSize()]));
String plainText = new String(cipher.doFinal(cipherText.getBytes()));
return plainText;
}
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
return data;
}
}
The output of the cipher is a sequence of random-looking bytes. You have no guarantee that these bytes will be a valid encoding for a character string in whatever is your system's default encoding. So this line:
String cipherText = new String(cipher.doFinal(.....));
is likely to lose information that you'll need for decryption.
Therefore you will not get the right bytes reconstructed in your decrypt operation. For example, if your default encoding is UTF-8, it is overwhelmingly unlikely that the correct ciphertext is something that String.getBytes() is even able to produce.
Two things:
No padding can only work if you use input that is an exact mulitple of your key size, which is 128 bit or 16 bytes. So in your particular case "Hello World!!!!!".getBytes() is actually a multiple of 16, but this is of course not true for arbitrary Strings.
Use "AES/CBC/PKCS5Padding" instead to solve this issue.
Do not turn your encrypted data into a String - this will and change the encrypted output. There's no guarantee that new String(byte[]).getBytes() returns the exact same byte array!
So you should leave the encrypted data as what it is - a stream of bytes. Thus encrypt should return byte[] instead and decrypt should take byte[] as input - this is a working example:
public class NewClass {
public static void main(String [] args) {
try {
String plainText = "Hello World!!!!";
String encryptionKey = "E072EDF9534053A0B6C581C58FBF25CC";
System.out.println("Before encryption - " + plainText);
byte[] cipherText = encrypt(plainText, encryptionKey);
System.out.println("After encryption - " + cipherText);
String decrypted = decrypt(cipherText, encryptionKey);
// -> Hello World!!!!
System.out.println("After decryption - " + decrypted);
} catch (Exception e) {
e.printStackTrace();
}
}
public static byte[] encrypt(String plainText, String passkey) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE");
SecretKeySpec key = new SecretKeySpec(hexStringToByteArray(passkey), "AES");
cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(new byte[cipher.getBlockSize()]));
return cipher.doFinal(plainText.getBytes());
}
public static String decrypt(byte[] cipherText, String passkey) throws Exception{
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE");
SecretKeySpec key = new SecretKeySpec(hexStringToByteArray(passkey), "AES");
cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(new byte[cipher.getBlockSize()]));
return new String(cipher.doFinal(cipherText));
}
You need to create the SecretKeySpec object once and use it for both encrypt and decrypt. Currently the code is creating two different keys for each operation and this will definitely lead to incorrect results.

How do I encrypt/decrypt a string of text using 3DES in java? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How do I use 3des encryption/decryption in Java?
How do I encrypt/decrypt a string of text using 3DES in java?
I found my answer. Duplicate question that didn't show up when I asked this one.
How do I use 3des encryption/decryption in Java?
From an old code:
public void testSymCypher(SecretKey k, String str)
throws BadPaddingException, IllegalBlockSizeException,
InvalidAlgorithmParameterException, InvalidKeyException,
NoSuchAlgorithmException, NoSuchPaddingException
{
Cipher cip = Cipher.getInstance("DESede/CBC/PKCS5Padding");
cip.init(Cipher.ENCRYPT_MODE,k);
byte[] ciphered = cip.doFinal(str.getBytes());
byte iv[] = cip.getIV();
// printing the ciphered string
printHexadecimal(ciphered);
IvParameterSpec dps = new IvParameterSpec(iv);
cip.init(Cipher.DECRYPT_MODE,k,dps);
byte[] deciphered = cip.doFinal(ciphered);
// printing the deciphered string
printHexadecimal(deciphered);
}
Notice than other usage of DESede are available in Java JDK 6:
DESede/CBC/NoPadding (168)
DESede/CBC/PKCS5Padding (168)
There is also ECB mode available (but be carreful to not use it twice !!), you don't need to use iv part in this case:
DESede/ECB/NoPadding (168)
DESede/ECB/PKCS5Padding (168)
To generate key for DESede:
KeyGenerator generatorDes = KeyGenerator.getInstance("DESede");
SecretKey skaes = generatorDes.generateKey();
Finally I recommand reading this document from SUN if you need to work on Java and Cryptography
We use this little helper class for password-based DES encryption from String to Hex String and back - not sure how to get this working with 3DES though:
import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
public class DesHelper {
private static org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(DesHelper.class);
static final byte[] SALT = { (byte) 0x09, /* snip - randomly chosen but static salt*/ };
static final int ITERATIONS = 11;
private Cipher _ecipher;
private Cipher _dcipher;
public DesHelper(final String passphrase) {
try {
final PBEParameterSpec params = new PBEParameterSpec(SALT, ITERATIONS);
final KeySpec keySpec = new PBEKeySpec(passphrase.toCharArray());
final SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES")
.generateSecret(keySpec);
_ecipher = Cipher.getInstance(key.getAlgorithm());
_dcipher = Cipher.getInstance(key.getAlgorithm());
_ecipher.init(Cipher.ENCRYPT_MODE, key, params);
_dcipher.init(Cipher.DECRYPT_MODE, key, params);
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
public String encrypt(final String string) {
try {
// Encode the string into bytes using utf-8
final byte[] bytes = string.getBytes("UTF-8");
// Encrypt
final byte[] enc = _ecipher.doFinal(bytes);
// Encode bytes to base64 to get a string
return bytesToHex(enc);
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
public String decrypt(final String str) {
try {
// Decode base64 to get bytes
final byte[] dec = hexToBytes(str);
// Decrypt
final byte[] utf8 = _dcipher.doFinal(dec);
// Decode using utf-8
return new String(utf8, "UTF8");
} catch (final Exception e) {
log.info("decrypting string failed: " + str + " (" + e.getMessage() + ")");
return null;
}
}
private static String bytesToHex(final byte[] bytes) {
final StringBuilder buf = new StringBuilder(bytes.length * 2);
for (final byte b : bytes) {
final String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
buf.append("0");
}
buf.append(hex);
}
return buf.toString();
}
private static byte[] hexToBytes(final String hex) {
final byte[] bytes = new byte[hex.length() / 2];
for (int i = 0; i < bytes.length; i++) {
bytes[i] = (byte) Integer.parseInt(hex.substring(i * 2, i * 2 + 2), 16);
}
return bytes;
}
}
You would use this class like this:
public static void main(final String[] args) {
final DesHelper h = new DesHelper("blabla");
System.out.println(h.decrypt(h.encrypt("foobar")));
}
I wrote an article on this sometimes back. Please visit the following link in my blog that has a working, completed code with explanations and diagram.
View My Triple DES Encryption Article, Code Here
Hopefully you will find it helpful.
You may also consider using a stream cipher (e.g., OFB or CTR mode on top of a 3DES block encryption), so that you don't have to deal with padding the string to a multiple of the cipher blocksize.

Categories

Resources