我正在研究 AES 算法,但我遇到了无法解决的异常。
javax.crypto.BadPaddingException: Given final block not properly padded
at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
at com.sun.crypto.provider.AESCipher.engineDoFinal(DashoA13*..)
at javax.crypto.Cipher.doFinal(DashoA13*..)
异常发生在解密部分。 我在与解密算法不同的地方初始化 key
KeyGenerator kgen = KeyGenerator.getInstance("AES");//key generation for AES
kgen.init(128); // 192 and 256 bits may not be available
然后我将它与我从文件中读取的密文一起传递给以下方法
public String decrypt(String message, SecretKey skey) {
byte[] raw = skey.getEncoded();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
// Instantiate the cipher
Cipher cipher;
byte[] original = null;
try {
cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
System.out.println("Original string: "
+ message);
original = cipher.doFinal(message.trim().getBytes()); //here where I got the exception
String originalString = new String(original);
}
//catches
编辑 这是加密方法。
public String encrypt(String message, SecretKey skey) {
byte[] raw = skey.getEncoded();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
// Instantiate the cipher
Cipher cipher;
byte[] encrypted = null;
try {
cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
encrypted = cipher.doFinal(message.getBytes());
System.out.println("raw is " + encrypted);
} catches
return asHex(encrypted);
}
这里是 asHex 方法
public static String asHex(byte buf[]) {
StringBuffer strbuf = new StringBuffer(buf.length * 2);
int i;
for (i = 0; i < buf.length; i++) {
if (((int) buf[i] & 0xff) < 0x10) {
strbuf.append("0");
}
strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
}
return strbuf.toString();
}
这是我从文件中读取密文的地方
static public String readFile(String filePath) {
StringBuilder file = new StringBuilder();
String line = null;
try {
FileReader reader = new FileReader(filePath);
BufferedReader br = new BufferedReader(reader);
if (br != null) {
line = br.readLine();
while (line != null) {
file.append(line);
// System.out.println("line is " + line);
line = br.readLine();
}
}
br.close();
reader.close();
} catch (IOException ex) {
Logger.getLogger(FileManagement.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("line is " + file.toString());
return String.valueOf(file);
}
有人可以帮忙吗?
最佳答案
好的,所以问题是您将加密的字节转换为十六进制字符串(使用 asHex 方法),但没有将十六进制字符串正确转换回字节数组以进行解密。你不能使用 getBytes。
您可以使用以下 method将十六进制字符串转换为字节数组:
public static byte[] fromHexString(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
return data;
}
然后更改要使用的解密方法:
original = cipher.doFinal(fromHexString(message));
关于javax.crypto.BadPaddingException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4580982/
我正在尝试解密使用OpenSSL命令行界面创建的文件。此文件创建于:opensslaes-256-cbc-a-infile.txt-outfile_encrypted.txt并且可以用以下方法解密:opensslaes-256-cbc-d-a-infile_encrypted.txt通过使用-p标志,我可以检索WebCryptoAPI所需的实际值、salt和IV:>opensslaes-256-cbc-d-a-p-infile_encrypted.txtsalt=F57F1CC0CD384326key=0E971326890959386F1CFB91F185CFE109203DCEBC
我使用Crypto-JSsourcesiteatGooglecode中的示例进行了简单测试:在页眉中:在Javascript函数中:varencrypted=CryptoJS.AES.encrypt("Message","SecretPassphrase");vardecrypted=CryptoJS.AES.decrypt(encrypted,"SecretPassphrase");alert('encrypted:'+encrypted+'decrypted:'+decrypted);但是输出是:encrypted:U2FsdGVkX19hsNqFBS5xcUoVBCu/hPHep
我收到以下错误:TypeError:__WEBPACK_IMPORTED_MODULE_0_aws_sdk_global__.util.crypto.lib.randomBytesisnotafunction当我尝试使用我编写的以下代码对用户进行身份验证时:import{CognitoUserPool,CognitoUserAttribute,CognitoUser,AuthenticationDetails}from'amazon-cognito-identity-js';letauthenticationDetails=newAuthenticationDetails({Usern
我目前使用以下设置来注册新用户://createsanewuserapp.post('/users',function(req,res){//createnewuservaruser=newUser();//assignpostuser.username=req.body.username;user.email=req.body.email;crypto.randomBytes(32,function(err,buf){if(err)throwerr;user.salt=buf.toString('hex');crypto.pbkdf2(req.body.password,user.s
我正在尝试通过Java调用JavaScript中的函数。这在直接将脚本作为字符串读取时效果很好,但我使用的是CompiledScripts。当我使用编译脚本执行此操作时,如果我还添加绑定(bind),它会提示找不到方法。没有绑定(bind)它可以工作,但当然函数失败,因为它需要绑定(bind)。有什么想法吗?CompiledScriptscript=...getscript....Bindingsbindings=script.getEngine().createBindings();LoggerscriptLogger=LogManager.getLogger("TEST_SCRIP
我们使用CryptoJSSHA3将我们的用户名和密码哈希在一起。该函数从两个html输入字段获取用户名和密码的输入,将它们与盐连接起来,并对它们进行哈希处理。第一个散列成功运行,但是再次散列相同的输出会产生不同的结果。这是相关代码:$prehash=$salt+$user+$pass;$prehash=CryptoJS.enc.Utf8.parse($prehash);varsha3=CryptoJS.algo.SHA3.create();sha3.update($prehash);varpassword=sha3.finalize().toString(CryptoJS.enc.He
我是NodeJs的新手,正在尝试弄清楚如何使用“crypto”模块。在玩弄它时,我注意到NodeJs和crypto-js中的“crypto”模块之间的区别:使用crypto-js,我有:functionSHA256Hash(password,salt,iteration){varsaltedpassword=salt+password;varsha256=CryptoJS.algo.SHA256.create();for(vari=0;i然后调用:varhashedPassword=SHA256Hash("123456789","ASIN",3)并接收:saltedpassword=A
我已经无计可施了。知道网络worker无法访问window对象,有什么办法可以做到这一点吗?请帮忙! 最佳答案 我知道这是一个老问题,但我偶然发现了这个问题,事情发生了变化。大多数浏览器现在都支持网络worker中的加密。在webworkers中,您可以访问self,它不包含所有“窗口”属性(尤其是与dom无关的属性),但包含加密函数等API方法。因此,您可以从webworker中简单地访问self.crypto.getRandomValues()。我做了一个fiddle作为例子:http://jsfiddle.net/jbrosi
看起来Math.random()生成范围[0,1)中的64位float,而新的crypto.getRandomValues()API仅返回整数。使用此API在[0,1)中生成数字的理想方法是什么?这似乎可行,但似乎不是最理想的:ints=newUint32Array(2)window.crypto.getRandomValues(ints)returnints[0]/0xffffffff*ints[1]/0xffffffff编辑:澄清一下,我试图产生比Math.random()更好的结果。根据我对float的理解,应该可以得到52位随机数的完全随机分数。(?)编辑2:为了提供更多背景知
我正在尝试从文件中加载PFX和密码,以便发出HTTPS请求。在开始之前,我已经知道PFX很好,这不是问题所在。我正在做以下事情:config.options.pfx=fs.readFileSync('file.pfx');config.options.passphrase='passphrase';我正在将我的选项传递给代理。config.options.agent=newhttps.Agent(options);然后我尝试构建rquest,但出现以下错误:crypto.js:143c.context.loadPKCS12(pfx,passphrase);^Error:headerto