我正在努力将代码从java迁移到Nodejs。我有一个要求用私钥加密文本使用" DESede / ECB / NoPadding"算法。目前代码是用Java编写的,现在我需要迁移到Nodejs。由于加密密钥被发送到其他应用程序,因此我无法在此更改算法或密钥。以下是java中使用的方法
1. Stored the private key in hex string. I.e. 48 chars hex string as below which is equivalent to 24 bytes reuquired for 3des
73AD9CEC99816AA6A4D82FB273AD9CEC99816AA6A4D82FB2
2. Following is code written in java
https://github.com/dilipkumar2k6/3des/blob/master/TripleDes.java
import java.security.GeneralSecurityException;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class TripleDes {
// Crypto library related keys
private static final String ALGO_NAME = "DESede/ECB/NoPadding";
private static final int PADDING_BLOCK = 8;
// Test Data
private static final String PLAIN_TEXT = "Hello World";
private static final String SHARED_KEY = "73AD9CEC99816AA6A4D82FB273AD9CEC99816AA6A4D82FB2";
public static void main(String[] arg) {
try {
// Get Algorithm name
String desAlgoName = getDESAlgorithmName(ALGO_NAME);
// Create Cipher object
Cipher cipher = Cipher.getInstance(ALGO_NAME);
//Actual DES algo needs 56 bits key, which is equivalent to 1byte (0 at 0th position) Get 8*3 byets key
byte [] key = hexFromString(SHARED_KEY);
System.out.println("DES Algorithm shared key size in bytes >> "+key.length);
// Create SecretKeySpec
SecretKeySpec secretKeySpec = new SecretKeySpec(key, desAlgoName);
//Encrypt bytes
byte [] encryptedBytes = encryptIntoBytes(cipher, secretKeySpec, PLAIN_TEXT.getBytes(), 0, PLAIN_TEXT.getBytes().length);
String encryptedString= hexToString(encryptedBytes);
System.out.println(encryptedString);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static byte[] encryptIntoBytes(Cipher cipher, SecretKeySpec secretKeySpec, byte[] dct, int offset, int len) throws GeneralSecurityException {
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] ect = cipher.doFinal(addPadding(dct, offset, len));
return ect;
}
public static String getDESAlgorithmName(String algoName) {
System.out.println("getDESAlgorithmName algoName >> "+algoName);
String desAlgoName = null;
int i = algoName.indexOf("/");
if (i != -1)
desAlgoName = algoName.substring(0, i);
else
desAlgoName = algoName;
return desAlgoName;
}
/**
* Adds padding characters to the data to be encrypted. Also adds random
* Initial Value to the beginning of the encrypted data when using Triple
* DES in CBC mode (DES-EDE3/CBC).
*
* @param inData
* Array of bytes to be padded
* @param offset
* Offset to starting point within array
* @param len
* Number of bytes to be encrypted
* @return Padded array of bytes
*/
public static byte[] addPadding(byte[] inData, int offset, int len) {
System.out.println("addPadding offset >> "+offset+", len >> "+len);
byte[] bp = null;
int padChars = PADDING_BLOCK; // start with max padding value
int partial = (len + 1) % padChars; // calculate how many extra bytes
// exist
if (partial == 0) {
padChars = 1; // if none, set to only pad with length byte
} else {
padChars = padChars - partial + 1; // calculate padding size to
// include length
}
System.out.println("addPadding >> Add padding of "+padChars);
/*
* Create a byte array large enough to hold data plus padding bytes The
* count of padding bytes is placed in the first byte of the data to be
* encrypted. That byte is included in the count.
*/
bp = new byte[len + padChars];
bp[0] = Byte.parseByte(Integer.toString(padChars));
System.arraycopy(inData, offset, bp, 1, len);
return bp;
}
public static byte[] hexFromString(String hex) {
int len = hex.length();
byte[] buf = new byte[((len + 1) / 2)];
int i = 0, j = 0;
if ((len % 2) == 1)
buf[j++] = (byte) fromDigit(hex.charAt(i++));
while (i < len) {
buf[j++] = (byte) ((fromDigit(hex.charAt(i++)) << 4) | fromDigit(hex
.charAt(i++)));
}
return buf;
}
public static int fromDigit(char ch) {
if (ch >= '0' && ch <= '9')
return ch - '0';
if (ch >= 'A' && ch <= 'F')
return ch - 'A' + 10;
if (ch >= 'a' && ch <= 'f')
return ch - 'a' + 10;
throw new IllegalArgumentException("invalid hex digit '" + ch + "'");
}
public static String hexToString(byte[] ba) {
return hexToString(ba, 0, ba.length);
}
public static final char[] hexDigits = { '0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
public static String hexToString(byte[] ba, int offset, int length) {
char[] buf = new char[length * 2];
int j = 0;
int k;
for (int i = offset; i < offset + length; i++) {
k = ba[i];
buf[j++] = hexDigits[(k >>> 4) & 0x0F];
buf[j++] = hexDigits[k & 0x0F];
}
return new String(buf);
}
}
我需要将此代码迁移到Nodejs并面临多个问题。我重新考虑http://mygo.iteye.com/blog/2018882以获得nodejs在des3中进行加密的基本思路。但是我看到了JAVA方式和Nodejs方式的不同之处。
1. JAVA is using Hex string of 48 lenght as key, since one char in hex is 4 bits therfore final size is equivalent to 24 bytes length which meets DES3 requirement.
2. In Java code, final key is being used as bytes (as needed by DES) which made indpendent of the way we store the key
3. In node js, key is stored as character i.e. to use des3 I have to use 24 bytes which is equivalent to 24 chars key as 73AD9CEC99816AA6A4D82FB2. Here this is string of 24 chars and since one char is one byte thereofore total length is 24 bytes which meets DES3 requirement.
4. Following is nodejs code for reference
https://github.com/dilipkumar2k6/3des/blob/master/Crypto.js
'use strict';
/*
* Offers related services.
*/
var crypto = require("crypto");
module.exports = {
encrypt: function (plainText) {
return encrypt({
alg: 'des-ede3', //3des-ecb
autoPad: true,
key: '73AD9CEC99816AA6A4D82FB2',
plaintext: 'Hello World',
iv: null
});
}
};
function encrypt(param) {
var key = new Buffer(param.key);
var iv = new Buffer(param.iv ? param.iv : 0);
var plaintext = param.plaintext;
var alg = param.alg;
var autoPad = param.autoPad;
//encrypt
var cipher = crypto.createCipheriv(alg, key, iv);
cipher.setAutoPadding(autoPad); //default true
var ciph = cipher.update(plaintext, 'utf8', 'hex');
ciph += cipher.final('hex');
console.log(alg, ciph);
return ciph;
}
function decrypt(param) {
var key = new Buffer(param.key);
var iv = new Buffer(param.iv ? param.iv : 0)
var alg = param.alg;
var autoPad = param.autoPad;
//decrypt
var decipher = crypto.createDecipheriv(alg, key, iv);
cipher.setAutoPadding(autoPad);
var txt = decipher.update(ciph, 'hex', 'utf8');
txt += decipher.final('utf8');
console.log(alg, txt);
return txt;
}
以下是我的问题。
1. How can i convert my existing hex code into string? I used "hexToString" method (please check the java code)to convert hex into string. However getting weired character (this is also expected but problem is how i can use this transformed key in nodejs.
2. Can I pass byte array as key to Nodejs? It will make problem easy as I can easily convert my hex key into bytes array and I store my bytes array key in nodejs code.
3. In my javacode, I have custom padding logic, how can i write same logic in nodejs?
4. Most importantly, can I achieve same encryption logic in nodejs (similar to java)?
Artjom B.帮助我了解nodejs和des3算法。我编辑了我的帖子以澄清我的确切要求。
我认为我的主要问题是,如何将byte []作为DES3的nodejs加密密钥?
我有点卡住了。请帮忙。
答案 0 :(得分:3)
正在运行crypto.getCiphers()
会显示可用的密码。 ECB模式下具有两个密钥(16字节密钥)的三重DES(EDE)可用作des-ede
。如果您有三个部分密钥(24字节密钥),则应使用des-ede3
。 ecb
可能不会出现在密码描述中,因为它是最基本的形式。
Triple DES-EDE有不同的方法来使用密钥。 EDE表示使用三个不同的密钥进行加密 - 解密 - 加密。如果您只有一个8字节密钥,则表明您在EDE的每个阶段都使用相同的密钥。从Java代码中可以清楚地看到,您有一个24字节密钥(48个十六进制编码字符)。您必须使用相同的密钥。
加密模块默认使用PKCS7填充,因此您需要设置auto padding to false并自行填充。我把这个任务留给你了。
module.exports = {
encrypt: function (plainText) {
return encrypt({
alg: 'des-ede3', //3des-ecb
autoPad: false,
key: '73AD9CEC99816AA6A4D82FB273AD9CEC99816AA6A4D82FB2',
plaintext: 'Hello World',
iv: null
});
}
};
function mypad(buf){
// TODO: do the padding
// replicate padding as in Java
return buf;
}
function myunpad(buf){
// TODO: do the unpadding
// read the first *byte* and remove as many trailing *bytes*
return buf;
}
function encrypt(param) {
var key = new Buffer(param.key);
var iv = new Buffer(param.iv ? param.iv : 0);
var plaintext = mypad(new Buffer(param.plaintext));
var alg = param.alg;
var autoPad = param.autoPad;
//encrypt
var cipher = crypto.createCipheriv(alg, key, iv);
cipher.setAutoPadding(autoPad); //default true
var ciph = cipher.update(plaintext, 'utf8', 'hex');
ciph += cipher.final('hex');
console.log(alg, ciph);
return ciph;
}
function decrypt(param) {
var key = new Buffer(param.key);
var iv = new Buffer(param.iv ? param.iv : 0)
var alg = param.alg;
var autoPad = param.autoPad;
//decrypt
var decipher = crypto.createDecipheriv(alg, key, iv);
cipher.setAutoPadding(autoPad);
var txt = decipher.update(ciph, 'hex', 'utf8');
txt += decipher.final('utf8');
console.log(alg, txt);
return myunpad(new Buffer(txt, 'hex'));
}
提醒:
不要使用(3)DES,特别是只有一个8字节密钥!不要使用ECB模式!不要将NoPadding用于块模式!使用AES-256和GCM模式(没有填充,因为它是流模式).-
答案 1 :(得分:1)
这是我的解密功能,基于Artjom的答案。使用&#39; des-ede3&#39;如果你有一个24字节密钥。
internals.decrypt = function (message, key) {
var message = Buffer.from(message, 'base64');
var decipher = crypto.createDecipher('des-ede', key);
var decryptedMessage = decipher.update(message, 'hex', 'utf8');
decryptedMessage += decipher.final('utf8');
return decryptedMessage.toString();
}