0

我使用 DES 加密 nodeJs 中的字符串参数,但是如何在 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中的des解密:

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);
  }
}
4

0 回答 0