Java 将文本加密为 AES/CBC/PKCS7Padding
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29232705/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Encrypt text to AES/CBC/PKCS7Padding
提问by Shanty
I am developing a web application to encrypt some texts with java 6.
我正在开发一个 Web 应用程序来使用 java 6 加密一些文本。
The encrypted that I have to do is a AES (Rijndael) in CBC mode with PKCS7 padding and a 128-bit key.
我必须做的加密是带有 PKCS7 填充和 128 位密钥的 CBC 模式的 AES(Rijndael)。
I saw an article that explains how to encrypt in the same way I have to do, but with PKCS5 padding.
我看到了一篇文章,它解释了如何以与我必须做的相同的方式进行加密,但使用 PKCS5 填充。
The link of the article is here:
文章的链接在这里:
I change
我改变
private final static String cI = "AES/CBC/PKCS5Padding";
To
到
private final static String cI = "AES/CBC/PKCS7Padding";
But Java couldn't find a provider for this.
但是 Java 找不到为此提供程序。
Could someone tell me how I have to do?
有人能告诉我我该怎么办吗?
采纳答案by Artjom B.
Java only provides PKCS#5 padding, but it is the same as PKCS#7 padding. See this question on Crypto.SE:
Java 仅提供 PKCS#5 填充,但它与 PKCS#7 填充相同。在 Crypto.SE 上看到这个问题:
What is the difference between PKCS#5 padding and PKCS#7 padding
They are interchangeable for the common block ciphers like AES and DES.
它们对于常见的分组密码(如 AES 和 DES)是可互换的。
回答by Sani Singh Huttunen
The Java specification list a number of encryption modes (and paddings) that needs to be supported. PKCS7Padding
is not included.
Java 规范列出了许多需要支持的加密模式(和填充)。PKCS7Padding
不包括在内。
These are the AES/CBC modes any Java implementation must support.
这些是任何 Java 实现都必须支持的 AES/CBC 模式。
- AES/CBC/NoPadding (128 bit key)
- AES/CBC/PKCS5Padding (128 bit key)
- AES/CBC/NoPadding(128 位密钥)
- AES/CBC/PKCS5Padding(128 位密钥)
(See this answerfor more information)
(有关更多信息,请参阅此答案)
Bouncy Castledoes however have what you need.
然而,充气城堡确实有你需要的东西。
回答by Erick Martinez
Try this method
试试这个方法
String KEY_AES = "**************";
public String encrypt(String value) {
try {
byte[] key = KEY_AES.getBytes("UTF-8");
byte[] ivs = KEY_AES.getBytes("UTF-8");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
AlgorithmParameterSpec paramSpec = new IvParameterSpec(ivs);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, paramSpec);
return Base64.encodeToString(cipher.doFinal(value.getBytes("UTF-8")), Base64.DEFAULT);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}