使用Java加密节点和Decrypt

时间:2013-07-29 13:21:19

标签: java node.js encryption des

我使用DES来加密nodeJs中的String参数,但是如何在Java中正确使用DES解密。

在nodejs中,我使用此方法加密:https://github.com/ElmerZhang/ezcrypto/blob/master/lib/des.js

var DES = C.DES = {
_blockSize : 2,

_keyschedule : null,

_state : new State(),

_init : function(k) {
    this._keyschedule = new KeySchedule(k);
},

encrypt : function(message, password, options) {

    options = options || {};

    // Determine mode
    var mode = options.mode || new C.mode.OFB;

    // Allow mode to override options
    if (mode.fixOptions)
        mode.fixOptions(options);

    var
    // Convert to bytes if message is a string
    m = (message.constructor == String ? UTF8.stringToBytes(message)
            : message),

    // Generate random IV
    iv = options.iv || util.randomBytes(8),

    // Generate key
    k = (password.constructor == String ?
    // Derive key from passphrase
    C.PBKDF2(password, iv, 8, {
        asBytes : true
    }) :
    // else, assume byte array representing cryptographic key
    password);

    // Create key schedule
    this._keyschedule = new KeySchedule(k);

    // Encrypt
    mode.encrypt(DES, m, iv);

    // Return ciphertext
    m = options.iv ? m : iv.concat(m);
    return (options && options.asBytes) ? m : util.bytesToBase64(m);
},

_encryptBlock : function(message, offset) {
    this._state.initialPerm(message, offset);
    for ( var i = 0; i <= 15; i++) {
        this._state.round(this._keyschedule.getKey(i));
    }
    this._state.finalPerm(message, offset);
}

};

这是我在java中的解密:

public class DES {

  private static byte[] iv = {1,2,3,4,5,6,7,8};

  public static String encryptDES(String encryptString, String encryptKey) throws Exception {
    IvParameterSpec zeroIv = new IvParameterSpec(iv);
    SecretKeySpec key = new SecretKeySpec(encryptKey.getBytes(), "DES");
    Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
    byte[] encryptedData = cipher.doFinal(encryptString.getBytes());

    return Base64.encode(encryptedData);
  }

  public static String decryptDES(String decryptString, String decryptKey) throws Exception {
    byte[] byteMi = new Base64().decode(decryptString);
    IvParameterSpec zeroIv = new IvParameterSpec(iv);
    SecretKeySpec key = new SecretKeySpec(decryptKey.getBytes(), "DES");
    Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
    cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);
    byte decryptedData[] = cipher.doFinal(byteMi);

    return new String(decryptedData);
  }
}

0 个答案:

没有答案