AES在项目中的使用
2015-12-18 16:03
232 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/xiaoxiang8385/article/details/50352397
AES在项目中的使用
Java AES 加解密。
/* * 加密方法 */ public static String encrypt(String message){ byte[] unencrypted = message.getBytes(Charset.forName("utf-8")); byte[] aesKey = "0123456789123456".getBytes(); // 设置加密模式为AES的CBC模式 Cipher cipher = null; try { cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES"); IvParameterSpec iv = new IvParameterSpec(Arrays.copyOfRange(aesKey, 0, 16)); try { cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (InvalidAlgorithmParameterException e) { e.printStackTrace(); } // 加密 byte[] encrypted = null; try { encrypted = cipher.doFinal(unencrypted); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } // 使用BASE64对加密后的字符串进行编码 String base64Encrypted = new Base64().encodeToString(encrypted); System.out.println(base64Encrypted); return base64Encrypted; }
/* * 解密方法 */ public static String decode(String text){ byte[] aesKey = "0123456789123456".getBytes(); Cipher cipher = null; try { cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } SecretKeySpec key_spec = new SecretKeySpec(aesKey, "AES"); IvParameterSpec iv = new IvParameterSpec(Arrays.copyOfRange(aesKey, 0, 16)); try { cipher.init(Cipher.DECRYPT_MODE, key_spec, iv); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (InvalidAlgorithmParameterException e) { e.printStackTrace(); } // 使用BASE64对密文进行解码 byte[] encrypted = Base64.decodeBase64(text); // 解密 byte[] original = null; try { original = cipher.doFinal(encrypted); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } String str = new String(original); return str; }
相关文章推荐
- Vue项目使用AES做加密
- AES加密解密——AES在JavaWeb项目中前台JS加密,后台Java解密的使用
- vue项目中使用AES实现密码加密解密(ECB和CBC两种模式)
- AES加密解密——AES在JavaWeb项目中前台JS加密,后台Java解密的使用
- Java使用AES加密和解密的实例详解
- 使用Python进行AES加密和解密的示例代码
- 使用 NDoc 对 asp.net (Web) 项目产生文档的方法
- 使用Log4j为项目配置日志输出应用详解以及示例演示的实现分析
- 使用CVS做.NET项目
- 修改OleDB provider 移植 Data Application Blocks项目中使用存储过程的应用(Oracle or MsSqlServer)到Microsoft Access
- 为公司一个项目写的一个数据库操作类,使用了SQL Relay
- 使用UML进行项目开发
- 项目交付使用后问题
- 在项目中使用第三方组件/库的补充说明
- 有关Web项目使用EnterpriseLibrary的Sercurity问题
- [蛙蛙王子]项目中是否使用存储过程
- 在小型项目中使用 IBM Rational Unified Process: 极限编程剖析
- 几个以前项目中使用的函数 (转)
- 三层结构B/S项目中使用Enterprise Library---Data Access Application Block
- vs.net web项目使用visual source safe进行源代码管理