- //java代码
- KeyGenerator kg = KeyGenerator.getInstance("AES"); //获取密匙生成器
- kg.init(256); //初始化
- //DES算法必须是56位
- //DESede算法可以是112位或168位
- //AES算法可以是128、192、256位
- SecretKey key = kg.generateKey(); //生成密匙,可用多种方法来保存密匙
- //加密
- Cipher cp = Cipher.getInstance("AES"); //创建密码器
- cp.init(Cipher.ENCRYPT_MODE, key); //初始化
- String str = "我是需要被加密的明文";
- byte [] ptext = str.getBytes("UTF8");
- byte [] ctext = cp.doFinal(ptext); //加密
- //解密
- Cipher cp = Cipher.getInstance("AES"); //创建密码器
- cp.init(Cipher.DECRYPT_MODE, key); //初始化
- byte [] ptext = cp.doFinal(ctext); //解密
- String str = new String(ptext, "UTF8"); //重新显示明文
- //该片段来自于http://www.codesnippet.cn/detail/240420132978.html
来源: http://www.codesnippet.cn/detail/240420132978.html