AES前后加密算法代码

 首先下载 aes.js加密工具类:

 本文采用的是 AES/ECB/PKCS5Padding的加密方式进行加密的:

 js加密写法如下: 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>

<script src="aes.js"></script>
<body>


<script>

   

    var key = CryptoJS.enc.Utf8.parse("8NONwyJtHesysWpM");

    var plaintText = 'ABCDEFGH'; // 明文

    var encryptedData = CryptoJS.AES.encrypt(plaintText, key, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    });

    console.log("加密前:"+plaintText);
    console.log("加密后:"+encryptedData);

    encryptedData = encryptedData.ciphertext.toString();

    var encryptedHexStr = CryptoJS.enc.Hex.parse(encryptedData);
    var encryptedBase64Str = CryptoJS.enc.Base64.stringify(encryptedHexStr);

    var decryptedData = CryptoJS.AES.decrypt(encryptedBase64Str, key, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    });

    var decryptedStr = decryptedData.toString(CryptoJS.enc.Utf8);

    console.log("解密后:"+decryptedStr);

    
     var pwd = "PCsUFtgog9/qpqmqXsuCRQ==";
    //加密服务端返回的数据
    var decryptedData = CryptoJS.AES.decrypt(pwd, key, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    });
    
    console.log("解密服务端返回的数据:"+decryptedStr);

</script>
</body>
</html>

 Java加解密类: 

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.net.util.Base64;  

public class AESUtil {
    public static String encrypt(String input, String key){
      byte[] crypted = null;
      try{
        SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
          Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
          cipher.init(Cipher.ENCRYPT_MODE, skey);
          crypted = cipher.doFinal(input.getBytes());
        }catch(Exception e){
            System.out.println(e.toString());
        }
        return new String(Base64.encodeBase64(crypted));
    }

    public static String decrypt(String input, String key){
        byte[] output = null;
        try{
          SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
          Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
          cipher.init(Cipher.DECRYPT_MODE, skey);
          output = cipher.doFinal(Base64.decodeBase64(input));
        }catch(Exception e){
          System.out.println(e.toString());
        }
        return new String(output);
    }
    
    public static void main(String[] args) {
      String key = "8NONwyJtHesysWpM";
      String data = "ABCDEFGH";
      System.out.println(AESUtil.decrypt(AESUtil.encrypt(data, key), key));
      System.out.println(AESUtil.encrypt(data, key));        
    }    
}

 

posted @ 2018-02-23 15:21  shawWey  阅读(1997)  评论(0编辑  收藏  举报