crypto,js,java加密解密

2017 / 11 / 30 crypto

aes128模式,js加密,java解密的例子

js

'use strict';
var CryptoJS = require("crypto-js");

// Encrypt
var word = 'hello world';
var key = 'd8cg8gVakEq9Agup'
console.log(word);

key = CryptoJS.enc.Utf8.parse(key);
word = CryptoJS.enc.Utf8.parse(word);

var encrypted = CryptoJS.AES.encrypt(word, key, {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});
console.log(encrypted.toString());

var decryptedData = CryptoJS.AES.decrypt(encrypted.toString(), key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
});
var decryptedStr = decryptedData.toString(CryptoJS.enc.Utf8);
console.log(decryptedStr);

java


import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;

public class Encrypt {
    final static String ALGORITHMSTR = "AES/ECB/PKCS5Padding";

    /**
     */

    /*******************************************************************
     * 使用AES-128-CBC加密模式,key需要为16位。
     * */

    public static String Decrypt(String sSrc, String decryptKey) throws Exception {
        try {
            byte[] encryptBytes = new BASE64Decoder().decodeBuffer(sSrc);
            Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));
            byte[] decryptBytes = cipher.doFinal(encryptBytes);
            return new String(decryptBytes);
        }catch (Exception e) {
            e.printStackTrace();
            throw new Exception("sSrc="+sSrc+",key="+decryptKey);
        }
    }

    /**
     * AES加密为base 64 code
     * @param content 待加密的内容
     * @param encryptKey 加密密钥
     * @return 加密后的base 64 code
     * @throws Exception
     */
    public static String aesEncrypt(String content, String encryptKey) throws Exception {
        return new BASE64Encoder().encode(aesEncryptToBytes(content, encryptKey));
    }
    private static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));

        return cipher.doFinal(content.getBytes("utf-8"));
    }
}

注意事项

  • 待补充