I\'m trying to encrypt a string in java, send it to my node.js server, and decrypt it. However, when I try to do this I get keep getting errors when trying to decrypt.
Java crypto's default mode for DES is ECB, which you need to specify in nodejs:
var decipher = crypto.createDecipheriv('des-ecb', key, new Buffer(0))
var txt = decipher.update(encrypt_text, 'hex', 'utf8');
txt += decipher.final('utf8')
return txt
When you create the decipher object on the node server, you are passing a password rather than an actual key. In order to specify the actual key, you need to use crypto.createDecipheriv()
, but this requires an actual IV
(this example uses 8 null bytes, but that's not recommended for real encryption; Initialization Vector on wikipedia)
I was able to get your example working by explicitly specifying padding, block mode, and IV:
String privateKey = "someprivatekey";
String data = "dataToEncrypt";
DESKeySpec keySpec = new DESKeySpec(privateKey.getBytes("UTF-8"));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey key = keyFactory.generateSecret(keySpec);
byte[] dataToBytes = data.getBytes("UTF-8");
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(new byte[8]));
// send this string to server
String encryptedStr = Base64.encodeToString(cipher.doFinal(dataToBytes), 0);
The decryption version also explicitly specifies the block mode (des-cbc), and correctly truncates the key text to the first 8 bytes:
var privateKey = 'someprivatekey';
var textToDecipher = '9Y8GTNxhQkKSIm5pmH91VA=='; // Text "dataToEncrypt" encrypted using DES using CBC and PKCS5 padding with the key "someprivatekey"
var iv = new Buffer(8);
iv.fill(0);
var decipher = crypto.createDecipheriv('des-cbc', privateKey.substr(0,8), iv);
var dec = decipher.update(textToDecipher, 'base64', 'utf8');
dec += decipher.final('utf8');
console.log('deciphered: ' + dec);