AES前后端加密
Posted yw-ah
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了AES前后端加密相关的知识,希望对你有一定的参考价值。
1、前端代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script src="js/rollups/tripledes.js"></script> <script src="js/components/aes.js"></script> <script src="js/components/mode-ecb-min.js"></script> </head> <body> <input id="test" name="gj"> <button onclick="test()">点击</button> <script> function test(){ var param = $("input[name=‘gj‘]").val(); Encrypt(param); } var key = CryptoJS.enc.Utf8.parse(‘sadaasdsad‘); function Encrypt(word){ var srcs = CryptoJS.enc.Utf8.parse(word); var encrypted = CryptoJS.AES.encrypt(srcs, key, {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7}); console.log(encrypted.toString()); } function Decrypt(word) { var decrypt = CryptoJS.AES.decrypt(word, key, {mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7}); return CryptoJS.enc.Utf8.stringify(decrypt).toString(); } </script> </body> </html>
2、后端JAVA代码
import javax.crypto.*; import javax.crypto.spec.SecretKeySpec; import org.apache.commons.codec.binary.Base64; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.logging.Level; import java.util.logging.Logger; /** * @Author:yw * @Description:AES 加密解密 * @Date: Created in 18:392018/6/11 */ public class AESUtil { private static final String KEY ="sadaasdsad" private static final String KEY_ALGORITHM = "AES"; private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";//默认的加密算法 /** * AES 加密操作 * * @param content 待加密内容 * @param password 加密密码 * @return 返回Base64转码后的加密数据 */ public static String encrypt(String content, String decryptKey) { try { Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);// 创建密码器 byte[] byteContent = content.getBytes("utf-8"); cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));// 初始化为加密模式的密码器 byte[] result = cipher.doFinal(byteContent);// 加密 return Base64.encodeBase64String(result);//通过Base64转码返回 } catch (Exception ex) { Logger.getLogger(AESUtil.class.getName()).log(Level.SEVERE, null, ex); } return null; } /** * AES 加密操作 * * @param content 待加密内容 * @param password 加密密码 * @return 返回Base64转码后的加密数据 */ public static String encrypt(String content) { try { Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);// 创建密码器 byte[] byteContent = content.getBytes("utf-8"); cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(KEY.getBytes(), "AES"));// 初始化为加密模式的密码器 byte[] result = cipher.doFinal(byteContent);// 加密 return Base64.encodeBase64String(result);//通过Base64转码返回 } catch (Exception ex) { Logger.getLogger(AESUtil.class.getName()).log(Level.SEVERE, null, ex); } return null; } /** * AES 解密操作 * * @param content * @param password * @return */ public static String decrypt(String content, String decryptKey) { try { //实例化 Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM); //使用密钥初始化,设置为解密模式 cipher.init(Cipher.DECRYPT_MODE,new SecretKeySpec(decryptKey.getBytes(), "AES")); //执行操作 byte[] result = cipher.doFinal(Base64.decodeBase64(content)); return new String(result, "utf-8"); } catch (Exception ex) { Logger.getLogger(AESUtil.class.getName()).log(Level.SEVERE, null, ex); } return null; } /** * AES 解密操作 * * @param content * @param password * @return */ public static String decrypt(String content) { try { //实例化 Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM); //使用密钥初始化,设置为解密模式 cipher.init(Cipher.DECRYPT_MODE,new SecretKeySpec(KEY.getBytes(), "AES")); //执行操作 byte[] result = cipher.doFinal(Base64.decodeBase64(content)); return new String(result, "utf-8"); } catch (Exception ex) { Logger.getLogger(AESUtil.class.getName()).log(Level.SEVERE, null, ex); } return null; } /** * 生成加密秘钥 * * @return */ private static SecretKeySpec getSecretKey(final String password) { //返回生成指定算法密钥生成器的 KeyGenerator 对象 KeyGenerator kg = null; try { kg = KeyGenerator.getInstance(KEY_ALGORITHM); //AES 要求密钥长度为 128 kg.init(128, new SecureRandom(password.getBytes())); //生成一个密钥 SecretKey secretKey = kg.generateKey(); return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);// 转换为AES专用密钥 } catch (NoSuchAlgorithmException ex) { Logger.getLogger(AESUtil.class.getName()).log(Level.SEVERE, null, ex); } return null; } public static void main(String[] args) { String content = "13958160820"; //0gqIDaFNAAmwvv3tKsFOFf9P9m/6MWlmtB8SspgxqpWKYnELb/lXkyXm7P4sMf3e System.out.println("加密前:" + content); System.out.println("加密密钥和解密密钥:" + KEY); String encrypt = encrypt(content, KEY); System.out.println(encrypt.length()+":加密后:" + encrypt); String decrypt = decrypt(encrypt, KEY); System.out.println("解密后:" + decrypt); } /* *//** * 加密 * @method encrypt * @param content 需要加密的内容 * @param password 加密密码 * @return * @throws * @since v1.0 *//* public static String encrypt(String content){ try { KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128, new SecureRandom(KEY.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 parseByte2HexStr(result);// 加密 } catch (NoSuchAlgorithmException e) { e.printStackTrace(); }catch (NoSuchPaddingException e) { e.printStackTrace(); }catch (UnsupportedEncodingException e) { e.printStackTrace(); }catch (InvalidKeyException e) { e.printStackTrace(); }catch (IllegalBlockSizeException e) { e.printStackTrace(); }catch (BadPaddingException e) { e.printStackTrace(); } return null; } *//** * 加密 * @method encrypt * @param content 需要加密的内容 * @param password 加密密码 * @return * @throws * @since v1.0 *//* public static String 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 parseByte2HexStr(result);// 加密 } catch (NoSuchAlgorithmException e) { e.printStackTrace(); }catch (NoSuchPaddingException e) { e.printStackTrace(); }catch (UnsupportedEncodingException e) { e.printStackTrace(); }catch (InvalidKeyException e) { e.printStackTrace(); }catch (IllegalBlockSizeException e) { e.printStackTrace(); }catch (BadPaddingException e) { e.printStackTrace(); } return null; } *//** * 解密 * @method decrypt * @param content 待解密内容 * @param password 解密密钥 * @return * @throws * @since v1.0 *//* public static String decrypt(String content, String password){ try { byte[] param = parseHexStr2Byte(content); 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(param); return new String(result); // 解密 } catch (NoSuchAlgorithmException e) { e.printStackTrace(); }catch (NoSuchPaddingException e) { e.printStackTrace(); }catch (InvalidKeyException e) { e.printStackTrace(); }catch (IllegalBlockSizeException e) { e.printStackTrace(); }catch (BadPaddingException e) { e.printStackTrace(); } return null; } *//** * 解密 * @method decrypt * @param content 待解密内容 * @param password 解密密钥 * @return * @throws * @since v1.0 *//* public static String decrypt(String content){ try { byte[] param = Base64.decodeBase64(parseHexStr2Byte(content)); KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128, new SecureRandom(KEY.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(param); return new String(result); // 解密 } catch (NoSuchAlgorithmException e) { e.printStackTrace(); }catch (NoSuchPaddingException e) { e.printStackTrace(); }catch (InvalidKeyException e) { e.printStackTrace(); }catch (IllegalBlockSizeException e) { e.printStackTrace(); }catch (BadPaddingException e) { e.printStackTrace(); } return null; } *//** * 将二进制转换成16进制 * @method parseByte2HexStr * @param buf * @return * @throws * @since v1.0 *//* 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(); } *//** * 将16进制转换为二进制 * @method parseHexStr2Byte * @param hexStr * @return * @throws * @since v1.0 *//* 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; } *//** * 另外一种加密方式--这种加密方式有两种限制 * 1、密钥必须是16位的 * 2、待加密内容的长度必须是16的倍数,如果不是16的倍数,就会出如下异常 * javax.crypto.IllegalBlockSizeException: Input length not multiple of 16 bytes at com.sun.crypto.provider.SunJCE_f.a(DashoA13*..) at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..) at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..) at com.sun.crypto.provider.AESCipher.engineDoFinal(DashoA13*..) at javax.crypto.Cipher.doFinal(DashoA13*..) 要解决如上异常,可以通过补全传入加密内容等方式进行避免。 * @method encrypt2 * @param content 需要加密的内容 * @param password 加密密码 * @return * @throws * @since v1.0 *//* public static byte[] encrypt2(String content, String password){ try { SecretKeySpec key = new SecretKeySpec(password.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding"); byte[] byteContent = content.getBytes("utf-8"); cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化 byte[] result = cipher.doFinal(byteContent); return result; // 加密 } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } return null; }*/ }
js链接地址:https://pan.baidu.com/s/1MtmtRxrIVQsBw9EpZsTAyQ 密码:aax3
这个地址也行:https://github.com/sytelus/CryptoJS/tree/master/components
以上是关于AES前后端加密的主要内容,如果未能解决你的问题,请参考以下文章