2021-10-08-java 实现 AES 加密解密算法

2021-10-08  本文已影响0人  一_贫

http://www.asfx.xyz/p/e3124067382f4c6a9fb1b43fc799b5e5

AES 的加密解决算法网上一大堆,但是大部分都没有解决一个问题,就是 windows 上测试正常,但在部分 linux 操作系统下却出现加密解密异常!比如会发现加密的结果值一直会变,这是因为实例化 SecureRandom 的方式不对造成的。
默认初始化方式为:

<pre class="prettyprint linenums prettyprinted" style="box-sizing: border-box; padding: 10px; margin: 0px 0px 16px; font: 400 12px / 1.6 Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace; overflow: auto; overflow-wrap: break-word; word-break: break-all; white-space: pre-wrap; overscroll-behavior-x: contain; border-radius: 3px; z-index: 0; color: rgb(204, 204, 204); background: rgb(246, 246, 246); border: 1px solid rgb(221, 221, 221); letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">

  1. generator.init(new SecureRandom(KEY_STR.getBytes()));

</pre>

需要改成

<pre class="prettyprint linenums prettyprinted" style="box-sizing: border-box; padding: 10px; margin: 0px 0px 16px; font: 400 12px / 1.6 Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace; overflow: auto; overflow-wrap: break-word; word-break: break-all; white-space: pre-wrap; overscroll-behavior-x: contain; border-radius: 3px; z-index: 0; color: rgb(204, 204, 204); background: rgb(246, 246, 246); border: 1px solid rgb(221, 221, 221); letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">

  1. SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
  2. random.setSeed(KEY_STR.getBytes());
  3. keygen.init(128, random);

</pre>

还有一点需要注意的是,建议 AES 加密结果用 Base64 再做加密处理,即使用下面工具类中的 encodeBase64 方法。因为只有 AES 加密的话结果值可能带有 + 号,这个作为参数在地址栏中使用的话会被当做拼接串处理,后端接收到这个值的时候会被解析成 + 号变成空格的情况。
上一篇 下一篇

猜你喜欢

热点阅读