I have to decrypt the data which encrypted in java server. In java server encrypted text using triple des(mode:CFB8, padding:NoPadding) For decrypt, I tried encrypting such as java server Below is posted the java source code.
private final static String keyString = "123456789012345678901234";
private final static String ivString = "abcdefgh";
public static String encrypt(String data) throws Exception {
KeySpec keySpec = new DESedeKeySpec(keyString.getBytes());
SecretKey key = SecretKeyFactory.getInstance("DESede").generateSecret(keySpec);
IvParameterSpec iv = new IvParameterSpec(ivString.getBytes());
Cipher ecipher = Cipher.getInstance("DESede/CFB8/NoPadding");
ecipher.init(Cipher.ENCRYPT_MODE, key, iv);
byte[] valeur = data.getBytes("UTF-8");
byte[] enc = ecipher.doFinal(valeur);
return new String(Base64.encode(enc, Base64.DEFAULT), "UTF-8");
}
And below code is my code.
var key="123456789012345678901234";
var iv = "abcdefgh";
var iv1 = CryptoJS.enc.Utf8.parse(iv);
var key1 = CryptoJS.enc.Utf8.parse(key);
var encrypted = CryptoJS.TripleDES.encrypt("asdfg", key1, {
iv:iv1,
mode:CryptoJS.mode.CFB,
padding:CryptoJS.pad.NoPadding
});
But I can't get the same result of both.
When I changed "CFB8" to "CFB" in the Java code, I get the same result.
How can implement the CFB8 in CryptoJS?
CFB is mode of operation with a shift register. The encryption and decryption happens in segments which have the same size as the shift register and are smaller than the block size.
The problem is that CryptoJS' CFB implementation only supports segment sizes exactly the same as the block size of the used block cipher. This means that when you use AES it will be a segment size of 128-bit.
I've implemented a variable segment size version of CFB which supports all segment sizes that are a power of 2 including 1-bit up to the block size:
You should use an appropriate padding. CryptoJS uses PKCS#7 padding by default. The best padding for CFB8 would be no padding at all (which you already use).
Example:
Since this is using a random IV, the only way to see whether the Java and JavaScript implementations are compatible, is to encrypt in one and decrypt in the other in both directions.
Keep in mind that since the IV is random, you need to send it along with the ciphertext. Since it doesn't need to be secret, you can easily prepend it to the ciphertext and slice it off before decryption.
This code is a custom copy from my repository on GitHub: artjomb/cryptojs-extension.