最近项目需要选择一套对称加密算法,来满足前后端之间的加解密操作。初步打算前端使用crypto-js来实现,后端使用java本身的加密算法实现,但遇到了一个问题:java本身只支持NoPadding和PKCS5Padding,而crypto-js提供的padding方式没有PKCS5Padding,所以不得以,前后端最终使用PKCS7Padding来实现功能.因此只能通过引入第三方jar包的方式让jave支持pkcs7padding
引入依赖
1
2
3
4
5
|
<dependency> <groupId>org.bouncycastle</groupId> <artifactId>bcprov-jdk16</artifactId> <version> 1.46 </version> </dependency> |
完整代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
|
package com.hzjd.miniapp.util; import java.security.Security; import java.security.spec.AlgorithmParameterSpec; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang.StringUtils; import org.bouncycastle.jce.provider.BouncyCastleProvider; import com.sun.istack.internal.NotNull; public class AESUtil { private static final String CHARSET_NAME = "UTF-8" ; private static final String AES_NAME = "AES" ; // 加密模式 public static final String ALGORITHM = "AES/CBC/PKCS7Padding" ; // 密钥 public static final String KEY = "1954682168745975" ; // 偏移量 public static final String IV = "1954682168745975" ; static { Security.addProvider( new BouncyCastleProvider()); } /** * 加密 * * @param content * @param key * @return */ public String encrypt( @NotNull String content) { byte [] result = null ; try { Cipher cipher = Cipher.getInstance(ALGORITHM); SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(CHARSET_NAME), AES_NAME); AlgorithmParameterSpec paramSpec = new IvParameterSpec(IV.getBytes()); cipher.init(Cipher.ENCRYPT_MODE, keySpec, paramSpec); result = cipher.doFinal(content.getBytes(CHARSET_NAME)); } catch (Exception e) { e.printStackTrace(); } return Base64.encodeBase64String(result); } /** * 解密 * * @param content * @param key * @return */ public String decrypt( @NotNull String content) { try { Cipher cipher = Cipher.getInstance(ALGORITHM); SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(CHARSET_NAME), AES_NAME); AlgorithmParameterSpec paramSpec = new IvParameterSpec(IV.getBytes()); cipher.init(Cipher.DECRYPT_MODE, keySpec, paramSpec); return new String(cipher.doFinal(Base64.decodeBase64(content)), CHARSET_NAME); } catch (Exception e) { e.printStackTrace(); } return StringUtils.EMPTY; } public static void main(String[] args) { AESUtil aes = new AESUtil(); String contents = "121456465" ; String encrypt = aes.encrypt(contents); System.out.println( "加密后:" + encrypt); String decrypt = aes.decrypt(encrypt); System.out.println( "解密后:" + decrypt); } } |
总结
到此这篇关于Java实现AES/CBC/PKCS7Padding加解密的方法的文章就介绍到这了,更多相关Java实现AES/CBC/PKCS7Padding加解密内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://www.cnblogs.com/tiro996/archive/2020/08/12/13488237.html