AES加密算法

Posted xyhero

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了AES加密算法相关的知识,希望对你有一定的参考价值。

java和js实现aes加密解密,AES加密比DES加密更安全

1、页面引入js

<script type="text/javascript" src="./aes/aes.js"></script>
<script type="text/javascript" src="./aes/mode-ecb.js"></script>


2、AES加密方法
//AES加密
function Encrypt(word){
var key = CryptoJS.enc.Utf8.parse("abcdefgabcdefg12");
var srcs = CryptoJS.enc.Utf8.parse(word);
var encrypted = CryptoJS.AES.encrypt(srcs, key, {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});
return encrypted.toString();
}

技术分享图片

 

//AES解密
function Decrypt(word){
var key = CryptoJS.enc.Utf8.parse("abcdefgabcdefg12");
var decrypt = CryptoJS.AES.decrypt(word, key, {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});
return CryptoJS.enc.Utf8.stringify(decrypt).toString();
}

技术分享图片

 

测试:
alert(Encrypt("测试"));
alert(Decrypt(Encrypt("测试")));

3、加密账号密码

技术分享图片

 

4、Java引入工具类(文章最后)

5、使用工具类解密

username=EncryptUtils.aesDecrypt(username, "abcdefgabcdefg12");
password=EncryptUtils.aesDecrypt(password, "abcdefgabcdefg12");

技术分享图片

 


如果报错,试试:

byte[] decryptFrom =EncryptUtils.parseHexStr2Byte(user);
byte[] decryptResult = EncryptUtils.decrypt(decryptFrom, "abcdefgabcdefg12");
user = new String(decryptResult);
byte[] decryptFrom2 =EncryptUtils.parseHexStr2Byte(pwd);
byte[] decryptResult2 = EncryptUtils.decrypt(decryptFrom2, "abcdefgabcdefg12");
pwd = new String(decryptResult2);

技术分享图片

EncryptUtils.java
package com.util;

import java.math.BigInteger;  
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

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




import org.apache.commons.codec.binary.Base64;
  
import org.apache.commons.lang.StringUtils;

import sun.misc.BASE64Decoder;  
  
/** 
 * 编码工具类 
 * 实现aes加密、解密 
 */  
public class EncryptUtils {  
      
    /** 
     * 密钥 
     */  
    private static final String KEY = "abcdefgabcdefg12";  
      
    /** 
     * 算法 
     */  
    private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";  
  
//    public static void main(String[] args) throws Exception {  
//        String content = "ning11";  
//        String password = "@#$#@[email protected]#$#@!%^^%$";  
//        //加密  
//        System.out.println("加密前:" + content);  
//        byte[] encryptResult = encrypt(content, password);  
//        String encryptResultStr = parseByte2HexStr(encryptResult);  
//        System.out.println("加密后:" + encryptResultStr);  
//        //解密  
//        byte[] decryptFrom = parseHexStr2Byte(encryptResultStr);  
//        byte[] decryptResult = decrypt(decryptFrom,password);  
//        System.out.println("解密后:" + new String(decryptResult)); 
//    }
      
    /** 
     * aes解密 
     * @param encrypt   内容 
     * @return 
     * @throws Exception 
     */  
    public static String aesDecrypt(String encrypt) throws Exception {  
        return aesDecrypt(encrypt, KEY);  
    }  
      
    /** 
     * aes加密 
     * @param content 
     * @return 
     * @throws Exception 
     */  
    public static String aesEncrypt(String content) throws Exception {  
        return aesEncrypt(content, KEY);  
    }  
  
    /** 
     * 将byte[]转为各种进制的字符串 
     * @param bytes byte[] 
     * @param radix 可以转换进制的范围,从Character.MIN_RADIX到Character.MAX_RADIX,超出范围后变为10进制 
     * @return 转换后的字符串 
     */  
    public static String binary(byte[] bytes, int radix){  
        return new BigInteger(1, bytes).toString(radix);// 这里的1代表正数  
    }  
  
    /** 
     * base 64 encode 
     * @param bytes 待编码的byte[] 
     * @return 编码后的base 64 code 
     */  
    public static String base64Encode(byte[] bytes){  
        byte[] byte11 = Base64.encodeBase64(bytes);
        String byte1 = parseByte2HexStr(byte11);
//        return Base64.encodeBase64String(bytes);
        return byte1;
    }  
    /**将16进制转换为二进制 
     * @param hexStr 
     * @return 
     */  
    public static byte[] parseHexStr2Byte(String hexStr) {  
            if (hexStr.length() < 1)  
                    return null;  
            byte[] result = new byte[hexStr.length()/2];  
            for (int i = 0;i< hexStr.length()/2; i++) {  
                    int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);  
                    int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);  
                    result[i] = (byte) (high * 16 + low);  
            }  
            return result;  
    }  
    
    public static String parseByte2HexStr(byte buf[]) {  
        StringBuffer sb = new StringBuffer();  
        for (int i = 0; i < buf.length; i++) {  
                String hex = Integer.toHexString(buf[i] & 0xFF);  
                if (hex.length() == 1) {  
                        hex = ‘0‘ + hex;  
                }  
                sb.append(hex.toUpperCase());  
        }  
        return sb.toString();  
}  
  
    /** 
     * base 64 decode 
     * @param base64Code 待解码的base 64 code 
     * @return 解码后的byte[] 
     * @throws Exception 
     */  
    public static byte[] base64Decode(String base64Code) throws Exception{  
        return StringUtils.isEmpty(base64Code) ? null : new BASE64Decoder().decodeBuffer(base64Code);  
    }  
  
      
    /** 
     * AES加密 
     * @param content 待加密的内容 
     * @param encryptKey 加密密钥 
     * @return 加密后的byte[] 
     * @throws Exception 
     */  
    public 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"));  
    }  
  
  
    /** 
     * 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 base64Encode(aesEncryptToBytes(content, encryptKey));  
    }  
  
    /** 
     * AES解密 
     * @param encryptBytes 待解密的byte[] 
     * @param decryptKey 解密密钥 
     * @return 解密后的String 
     * @throws Exception 
     */  
     public static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception {  
            KeyGenerator kgen = KeyGenerator.getInstance("AES");  
            kgen.init(128);  
  
            Cipher cipher = Cipher.getInstance(ALGORITHMSTR);  
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));  
            byte[] decryptBytes = cipher.doFinal(encryptBytes);  
  
            return new String(decryptBytes);  
        }  
  
  
    /** 
     * 将base 64 code AES解密 
     * @param encryptStr 待解密的base 64 code 
     * @param decryptKey 解密密钥 
     * @return 解密后的string 
     * @throws Exception 
     */  
    public static String aesDecrypt(String encryptStr, String decryptKey) throws Exception { 
        
        
        return StringUtils.isEmpty(encryptStr) ? null : aesDecryptByBytes(base64Decode(encryptStr), decryptKey);  
    }  
    /**解密 
     * @param content  待解密内容 
     * @param password 解密密钥 
     * @return 
     */  
    public static byte[] decrypt(byte[] content, String password) {  
            try {  
                     KeyGenerator kgen = KeyGenerator.getInstance("AES");  
                     kgen.init(128, new SecureRandom(password.getBytes()));  
                     SecretKey secretKey = kgen.generateKey();  
                     byte[] enCodeFormat = secretKey.getEncoded();  
                     SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");              
                     Cipher cipher = Cipher.getInstance("AES");// 创建密码器  
                    cipher.init(Cipher.DECRYPT_MODE, key);// 初始化  
                    byte[] result = cipher.doFinal(content);  
                    return result; // 加密  
            }catch (Exception e) {  
                    e.printStackTrace();  
            }
            return null;  
    } 
    
    
    public static byte[] encrypt(String content, String password) {  
        try {             
                KeyGenerator kgen = KeyGenerator.getInstance("AES");  
                kgen.init(128, new SecureRandom(password.getBytes()));  
                SecretKey secretKey = kgen.generateKey();  
                byte[] enCodeFormat = secretKey.getEncoded();  
                SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");  
                Cipher cipher = Cipher.getInstance("AES");// 创建密码器  
                byte[] byteContent = content.getBytes("utf-8");  
                cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化  
                byte[] result = cipher.doFinal(byteContent);  
                return result; // 加密  
        } catch (Exception e) {  
                e.printStackTrace();  
        } 
        return null;  
}  
}  

Base64.java

package com.zbiti.android.zhxj.activity;
  
import java.io.ByteArrayOutputStream;  
import java.io.IOException;  
import java.io.OutputStream;  
  
  
  
public class Base64 {  
    private static final char[] legalChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();  
    /** 
     * data[]进行编码 
     * @param data 
     * @return 
     */  
        public static String encode(byte[] data) {  
            int start = 0;  
            int len = data.length;  
            StringBuffer buf = new StringBuffer(data.length * 3 / 2);  
  
            int end = len - 3;  
            int i = start;  
            int n = 0;  
  
            while (i <= end) {  
                int d = ((((int) data[i]) & 0x0ff) << 16)  
                        | ((((int) data[i + 1]) & 0x0ff) << 8)  
                        | (((int) data[i + 2]) & 0x0ff);  
  
                buf.append(legalChars[(d >> 18) & 63]);  
                buf.append(legalChars[(d >> 12) & 63]);  
                buf.append(legalChars[(d >> 6) & 63]);  
                buf.append(legalChars[d & 63]);  
  
                i += 3;  
  
                if (n++ >= 14) {  
                    n = 0;  
                    buf.append(" ");  
                }  
            }  
  
            if (i == start + len - 2) {  
                int d = ((((int) data[i]) & 0x0ff) << 16)  
                        | ((((int) data[i + 1]) & 255) << 8);  
  
                buf.append(legalChars[(d >> 18) & 63]);  
                buf.append(legalChars[(d >> 12) & 63]);  
                buf.append(legalChars[(d >> 6) & 63]);  
                buf.append("=");  
            } else if (i == start + len - 1) {  
                int d = (((int) data[i]) & 0x0ff) << 16;  
  
                buf.append(legalChars[(d >> 18) & 63]);  
                buf.append(legalChars[(d >> 12) & 63]);  
                buf.append("==");  
            }  
  
            return buf.toString();  
        }  
  
        private static int decode(char c) {  
            if (c >= ‘A‘ && c <= ‘Z‘)  
                return ((int) c) - 65;  
            else if (c >= ‘a‘ && c <= ‘z‘)  
                return ((int) c) - 97 + 26;  
            else if (c >= ‘0‘ && c <= ‘9‘)  
                return ((int) c) - 48 + 26 + 26;  
            else  
                switch (c) {  
                case ‘+‘:  
                    return 62;  
                case ‘/‘:  
                    return 63;  
                case ‘=‘:  
                    return 0;  
                default:  
                    throw new RuntimeException("unexpected code: " + c);  
                }  
        }  
  
        /** 
         * Decodes the given Base64 encoded String to a new byte array. The byte 
         * array holding the decoded data is returned. 
         */  
  
        public static byte[] decode(String s) {  
  
            ByteArrayOutputStream bos = new ByteArrayOutputStream();  
            try {  
                decode(s, bos);  
            } catch (IOException e) {  
                throw new RuntimeException();  
            }  
            byte[] decodedBytes = bos.toByteArray();  
            try {  
                bos.close();  
                bos = null;  
            } catch (IOException ex) {  
                System.err.println("Error while decoding BASE64: " + ex.toString());  
            }  
            return decodedBytes;  
        }  
  
        private static void decode(String s, OutputStream os) throws IOException {  
            int i = 0;  
  
            int len = s.length();  
  
            while (true) {  
                while (i < len && s.charAt(i) <= ‘ ‘)  
                    i++;  
  
                if (i == len)  
                    break;  
  
                int tri = (decode(s.charAt(i)) << 18)  
                        + (decode(s.charAt(i + 1)) << 12)  
                        + (decode(s.charAt(i + 2)) << 6)  
                        + (decode(s.charAt(i + 3)));  
  
                os.write((tri >> 16) & 255);  
                if (s.charAt(i + 2) == ‘=‘)  
                    break;  
                os.write((tri >> 8) & 255);  
                if (s.charAt(i + 3) == ‘=‘)  
                    break;  
                os.write(tri & 255);  
  
                i += 4;  
            }  
        }  
          
}  

 
























以上是关于AES加密算法的主要内容,如果未能解决你的问题,请参考以下文章

正确使用AES对称加密

正确使用AES对称加密

php与java通用AES加密解密算法

DES加密解密与AES加密解密

对称加密及AES加密算法

加密算法之AES