The following code is tested for short strings, in that case it decrypts the string nicely.
byte[] ciphertext = Base64.decode(myverylongstring,Base64.DEFAULT);
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(Charset.forName("UTF-8")), "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes(Charset.forName("UTF-8")));
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] decryptedtextByte = cipher.doFinal(ciphertext);
String decryptedtext = new String(decryptedtextByte); //Successfully decrypts the string
System.out.println("decryptedtext: " + decryptedtext);
[...]
} catch (BadPaddingException e) {
e.printStackTrace();
}
But if the string is too large I get fired the exception I mention.
What could I do so it decrypts the string correctly maintaining the same large string to decrypt?
Edit, well technically what's decrypted is a byte[], changing title and adding code to not cause possible confussion.
As you did not show the encryption and we do not know what kind of key you are using there are many possible reasons for failure. As well you did not show the imports so I could just argue what Base64-encoder is in use.
Below you find a simple program that does the en- and decryption a byte array that is much larger than the size you are using.
Edit:
Security warning: The code below uses a stringified key and static IV, uses single part encryption / decryption for a huge byte array, uses the older CBC mode.
Please do not copy below code or use it in production - it is for educational purposes only.
The code does not have any proper exception handling !
It generates a (random filled) byte array with the plaintext and gets the key & iv from strings that are converted to byte[] using the Standard.Charset "UFT-8".
That it's doing the encryption, convert the ciphertext to a Base64 encoded string followed by the decoding to a new ciphertext byte[] and decryption with the same key and iv.
In the end there is simple comparison of the plaintext and decryptedtext byte arrays.
My advice it is to check for any forgotten charset-setting and correct (means identical) usage of key and iv.
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.Arrays;
import java.util.Base64;
public class Main {
public static void main(String[] args) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
System.out.println("https://stackoverflow.com/questions/63143007/getting-badpaddingexception-due-to-byte-too-long-to-decipher");
byte[] plaintext = new byte[100000];
SecureRandom secureRandom = new SecureRandom();
secureRandom.nextBytes(plaintext); // generate a random filled byte array
byte[] key = "12345678901234567890123456789012".getBytes(StandardCharsets.UTF_8);
byte[] iv = "1234567890123456".getBytes(StandardCharsets.UTF_8);
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] ciphertextEnc = cipher.doFinal(plaintext);
String ciphertextBase64 = Base64.getEncoder().encodeToString(ciphertextEnc);
byte[] ciphertextDec = Base64.getDecoder().decode(ciphertextBase64);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] decryptedtextByte = cipher.doFinal(ciphertextDec);
System.out.println("decryptedtextByte equals plaintext: " + Arrays.equals(plaintext, decryptedtextByte));
}
}
Related
I am not a security expert.
I have a requirement to generate javax.crypto.SecretKey based on password and salt.
In the existing code, we already have logic to generate javax.crypto.SecretKey but not based on password and salt`.
Also, in the existing code we already encrypt and decrypt using the javax.crypto.SecretKey.
There is already lot of data in DB which is encrypted using existing encrypt code and I dont think I can change existing encrypt and decrypt logic.
I am getting below the error when I try to decrypt data using the key generated based on password and salt with existing decrypt code.
key.getAlgorithm(): DESede
encryptedData: [B#31dc339b
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.DESedeCipher.engineDoFinal(DESedeCipher.java:294)
at javax.crypto.Cipher.doFinal(Cipher.java:2168)
at com.arjun.mytest.PMAdminKeyTest.main(PMAdminKeyTest.java:41)
import java.security.KeyStore;
import java.security.Provider;
import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
public class PMAdminKeyTest {
public static void main(String[] args) throws Exception {
// Requirement is to generate Key based on password and salt
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
KeySpec keySpec = new PBEKeySpec("password".toCharArray(), "salt".getBytes(), 65536, 192);
SecretKey key = new SecretKeySpec(secretKeyFactory.generateSecret(keySpec).getEncoded(), "DESede");
System.out.println("key.getAlgorithm(): " + key.getAlgorithm());
byte[] data = "12345678".getBytes("UTF8");
// Existing encrypt and decrypt code. There is already lot of data in DB
// encrypted in this manner. I dont think I can change this code.
Cipher cipher = Cipher.getInstance(key.getAlgorithm() + "/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encryptedData = cipher.doFinal(data);
System.out.println("encryptedData: " + encryptedData.toString());
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decryptedData = cipher.doFinal(data);
System.out.println("decryptedData: " + decryptedData.toString());
}
}
The only issue I can see is that you pass the unencrypted data to the Cipher in decrypt mode, which won't work. (The cipher obviously cannot decrypt data which is not encrypted without getting odd results.)
So change
byte[] decryptedData = cipher.doFinal(data);
to
byte[] decryptedData = cipher.doFinal(encryptedData);
Then, everything works fine.
Altough I doubt this error exists in your productive code, so if you still have problems on that one, feel free to ask a new question.
You are not decrypting the encrypted data, you are simply trying to decrypt the original data.
Also while printing the data use UTF-8
import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
public class PMAdminKeyTest {
public static void main(String[] args) throws Exception {
// Requirement is to generate Key based on password and salt
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
KeySpec keySpec = new PBEKeySpec("password".toCharArray(), "salt".getBytes(), 65536, 192);
SecretKey key = new SecretKeySpec(secretKeyFactory.generateSecret(keySpec).getEncoded(), "DESede");
System.out.println("key.getAlgorithm(): " + key.getAlgorithm());
byte[] data = "12345678".getBytes("UTF8");
// Existing encrypt and decrypt code. There is already lot of data in DB
// encrypted in this manner. I dont think I can change this code.
Cipher cipher = Cipher.getInstance(key.getAlgorithm() + "/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encryptedData = cipher.doFinal(data);
System.out.println("encryptedData: " + encryptedData.toString());
cipher.init(Cipher.DECRYPT_MODE, key);
// Notice this
byte[] decryptedData = cipher.doFinal(encryptedData);
// while printing the data use UTF-8
System.out.println("decryptedData: " + new String(decryptedData, "UTF-8"));
}
}
I'm writing a encryption and decryption code as follows
import java.io.*;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.BadPaddingException;
import java.nio.file.Files;
import java.util.Scanner;
public class EncryptFile
{
public static void main(String args[]) throws IOException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException {
//Encrypt Mode
FileOutputStream outputStream = new FileOutputStream(new File("D:\\encryptedNewStringFile.txt"));
Key secretKey = new SecretKeySpec("encKey".getBytes(), "Blowfish");
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] getFileBytes = "writing a file using encryption ".getBytes();
byte[] outputBytes = cipher.doFinal(getFileBytes);
outputStream.write(outputBytes);
getFileBytes = "\n".getBytes();
outputBytes = cipher.doFinal(getFileBytes);
outputStream.write(outputBytes);
getFileBytes = "This is New Line 2 \nThis is NewLine 3".getBytes();
outputBytes = cipher.doFinal(getFileBytes);
outputStream.write(outputBytes);
outputStream.close();
//Decrypt Mode
File curFile = new File("D:\\encryptedNewStringFile.txt");
secretKey = new SecretKeySpec("encKey".getBytes(), "Blowfish");
cipher = Cipher.getInstance("Blowfish/ECB/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
getFileBytes = Files.readAllBytes(curFile.toPath());
outputBytes = cipher.doFinal(getFileBytes);
InputStream bai = new ByteArrayInputStream(outputBytes);
BufferedReader bfReader = new BufferedReader(new InputStreamReader(bai));
Scanner scan = new Scanner(bfReader);
while(scan.hasNextLine())
{
System.out.println(scan.nextLine());
}
}
}
here i have a problem in output which is the printed output has some extra symbols (i.e question marks and box symbols)in it.
The output i received is
Any suggestions will be really helpful thanks in advance
Cipher cipher = Cipher.getInstance("Blowfish");
is equivalent to
Cipher cipher = Cipher.getInstance("Blowfish/ECB/PKCS5Padding");
which means that each time you call cipher.doFinal additional padding is produced.
In order to write a file without intermittent padding, you should be using
outputBytes = cipher.update(getFileBytes);
and use cipher.doFinal only when writing the last time to the file. Then you will be able to use PKCS5Padding instead of NoPadding during decryption in order to remove the valid padding at the end automatically.
Security considerations:
ECB mode is bad and should not be used. There are only very few use cases where this makes sense to use. At least use CBC mode with a randomly generated IV. The IV doesn't need to be secret but only unpredictable. We usually prepend it to the ciphertext and slice it off before decryption. Since it has always a predefined length, this is easy to do.
Use an authenticated mode of operation like GCM or use a message authentication code like HMAC-SHA256 in order to detect and react to (malicious) manipulation of the ciphertext.
Blowfish should not be used today. Although it has no direct vulnerability, its small block size may open you up to different protocol based vulnerabilities. It would be advisable to use a block cipher with a block size of 128-bit. AES comes to mind.
Combining the answers from #Artjom B. and #The 5th column mouse you get a file encryption program that will encrypt a file with Blowfish in CBC mode. The encryption and decryption is done in chunks so large files (up to some GB) could get encrypted and decrypted without "out of memory errors".
The key is generated randomly, and you should keep in mind - without knowledge of the key no decryption of the file is possible.
output:
file encryption with Blowfish CBC mode
used key (Base64): jsErS04so1NCC7Jmds6Grr+0tPkNoaj0hx/izLaW5H8=
result encryption: true
result decryption: true
Security warning: the code has no exception handling, no correct file handling (e.g. overwriting without notice) and is for educational purpose only:
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
public class BlowfishCbcFileEncryption {
public static void main(String[] args) throws NoSuchPaddingException, NoSuchAlgorithmException, IOException,
InvalidKeyException, InvalidAlgorithmParameterException {
System.out.println("file encryption with Blowfish CBC mode");
String uncryptedFilename = "uncrypted.txt";
String encryptedFilename = "encrypted.enc";
String decryptedFilename = "decrypted.txt";
// random blowfish 256 key
byte[] key = new byte[32];
SecureRandom secureRandom = new SecureRandom();
secureRandom.nextBytes(key);
System.out.println("used key (Base64): " + base64Encoding(key));
// random iv
byte[] iv = new byte[8]; // blowfish iv is 8 bytes long
secureRandom.nextBytes(iv);
boolean result;
result = encryptCbcFileBufferedCipherOutputStream(uncryptedFilename, encryptedFilename, key, iv);
System.out.println("result encryption: " + result);
result = decryptCbcFileBufferedCipherInputStream(encryptedFilename, decryptedFilename, key);
System.out.println("result decryption: " + result);
}
public static boolean encryptCbcFileBufferedCipherOutputStream(String inputFilename, String outputFilename, byte[] key, byte[] iv)
throws IOException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, InvalidAlgorithmParameterException {
Cipher cipher = Cipher.getInstance("Blowfish/CBC/PKCS5Padding");
try (FileInputStream in = new FileInputStream(inputFilename);
FileOutputStream out = new FileOutputStream(outputFilename);
CipherOutputStream encryptedOutputStream = new CipherOutputStream(out, cipher);) {
out.write(iv);
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "Blowfish");
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] buffer = new byte[8096];
int nread;
while ((nread = in.read(buffer)) > 0) {
encryptedOutputStream.write(buffer, 0, nread);
}
encryptedOutputStream.flush();
}
if (new File(outputFilename).exists()) {
return true;
} else {
return false;
}
}
public static boolean decryptCbcFileBufferedCipherInputStream(String inputFilename, String outputFilename, byte[] key) throws
IOException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, InvalidAlgorithmParameterException {
byte[] iv = new byte[8]; // blowfish iv is 8 bytes long
Cipher cipher = Cipher.getInstance("Blowfish/CBC/PKCS5Padding");
try (FileInputStream in = new FileInputStream(inputFilename); // i don't care about the path as all is local
CipherInputStream cipherInputStream = new CipherInputStream(in, cipher);
FileOutputStream out = new FileOutputStream(outputFilename)) // i don't care about the path as all is local
{
byte[] buffer = new byte[8192];
in.read(iv);
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "Blowfish");
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
int nread;
while ((nread = cipherInputStream.read(buffer)) > 0) {
out.write(buffer, 0, nread);
}
out.flush();
}
if (new File(outputFilename).exists()) {
return true;
} else {
return false;
}
}
private static String base64Encoding(byte[] input) {
return Base64.getEncoder().encodeToString(input);
}
}
Each time you convert string into the byte array, you use default file encoding from your VM properties which is not UTF-8.
So, to fix this issue you have two options: to define the default encoding in java system properties:
System.setProperty("file.encoding", StandardCharsets.UTF_8.name());
or add the charset encoding by each converting of strings into bytes:
"writing a file using encryption ".getBytes(StandardCharsets.UTF_8);
I am developing a code in Java, in which when a user enters the key, the Initialization Vector and the ciphertext, the program returns the deciphered text, according to the AES / CBC / PKCS5Padding Mode.
This code is NOT working, and I would like someone to help me correct it, or to present a better code, please.
This Key, this Initialization Vector and this ciphertext were got from this website:
https://www.di-mgt.com.au/properpassword.html
That is, the plain text must return a simple "Hello World" message.
If you know of any Java code that does this, can you please post?
My code, which is experiencing a NullPointerException error:
package encryptdecryptvideo;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.ShortBufferException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
//import javax.crypto.*;
public class EncryptDecryptVideo {
byte[] input;
String inputString;
byte[] keyBytes = "9008873522F55634679EF64CC25E73354".getBytes();
byte[] ivBytes = "B8A112A270D9634EFF3818F6CCBDF5EC".getBytes();
SecretKeySpec key = new SecretKeySpec(keyBytes, "DES");
IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
Cipher cipher;
byte[] cipherText = "625F094A1FB1677521B6014321A807EC".getBytes();
int ctLength;
public static void main(String args[]) throws InvalidKeyException, InvalidAlgorithmParameterException, ShortBufferException, IllegalBlockSizeException, BadPaddingException {
EncryptDecryptVideo decryptionobject = new EncryptDecryptVideo();
decryptionobject.decrypt();
}
public void decrypt() throws InvalidKeyException, InvalidAlgorithmParameterException, ShortBufferException, IllegalBlockSizeException, BadPaddingException {
cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
byte[] plainText = new byte[cipher.getOutputSize(ctLength)];
int ptLength = cipher.update(cipherText, 0, ctLength, plainText);
ptLength+= cipher.doFinal(plainText, ptLength);
System.out.println("Plain: "+new String(plainText));
}
}```
Some points that are obvious without deep in further:
First: there is no Cipher instantiation like ("AES/CBC/PKCS5Padding").
Second: Your "SecretKeySpec" will transform the input to a DES-key (and not "AES" as you are asking for in the title).
Third: the "cipher.doFinal" call usually returns a byte array and not any integer value.
Fourth: All of your input data seem to be a hexstring that should be converted to a byte array by something like "hexStringToByteArray" and not by ".getBytes" directly.
Fifth: the webpage you linked to does not use the "password" as direct input to the cipher but performs a password derivation (like PBKDF2) that needs to get replicated in Java code as well.
Sixth: please do not use "DES" anymore as it is broken and UNSECURE.
My recommendation is to use another source for your encryption/decryption than https://www.di-mgt.com.au/properpassword.html.
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.
What am I doing wrong? I expected the Java program to print "private". My goal is to try to write the MessageEncryptor.decrypt ruby method in Java.
Ruby encryption (most code was taken from MessageEncryptor, but modified not to Marshal), but I've extracted it so that it's easier to see what's going on:
require 'openssl'
require 'active_support/base64'
#cipher = 'aes-256-cbc'
d = OpenSSL::Cipher.new(#cipher)
#secret = OpenSSL::PKCS5.pbkdf2_hmac_sha1("password", "some salt", 1024, d.key_len)
cipher = OpenSSL::Cipher::Cipher.new(#cipher)
iv = cipher.random_iv
cipher.encrypt
cipher.key = #secret
cipher.iv = iv
encrypted_data = cipher.update("private")
encrypted_data << cipher.final
puts [encrypted_data, iv].map {|v| ::Base64.strict_encode64(v)}.join("--")
Which printed:
tzFUIVllG2FcYD7xqGPmHQ==--UAPvdm3oN3Hog9ND9HrhEA==
Java code:
package decryptruby;
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 org.apache.commons.codec.binary.Base64;
public class DecryptRuby {
public static String decrypt(String encrypted, String pwd, byte[] salt)
throws Exception {
String[] parts = encrypted.split("--");
if (parts.length != 2) return null;
byte[] encryptedData = Base64.decodeBase64(parts[0]);
byte[] iv = Base64.decodeBase64(parts[1]);
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec spec = new PBEKeySpec(pwd.toCharArray(), salt, 1024, 256);
SecretKey tmp = factory.generateSecret(spec);
SecretKey aesKey = new SecretKeySpec(tmp.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, aesKey, new IvParameterSpec(iv));
byte[] result = cipher.doFinal(encryptedData);
return result.toString();
}
public static void main(String[] args) throws Exception {
String encrypted = "tzFUIVllG2FcYD7xqGPmHQ==--UAPvdm3oN3Hog9ND9HrhEA==";
System.out.println("Decrypted: " + decrypt(encrypted, "password", "some salt".getBytes()));
}
}
Which printed
Decrypted: [B#432a0f6c
This is the problem - or at least a problem:
byte[] result = cipher.doFinal(encryptedData);
return result.toString();
You're calling toString() on a byte array. Arrays don't override toString(). That won't give you what you want at all - as you can see. Instead, you need to write something like:
return new String(result, "UTF-8");
... but you need to know what encoding was used to turn the original string into bytes before encryption. It's not clear to me from the Ruby code what encoding is used, but if you can be explicit about it (ideally using UTF-8) it'll make your life a lot easier.
In short, I suspect this problem has nothing to do with encryption at all - it has everything to do with converting text to bytes in Ruby and then converting the same sequence of bytes back into a string in Java.
Of course the encryption may be failing as well but that's a different matter.