如何解密javascript中的文件,该文件由JAVA用AES加密

我用AES256加密了Java中的JPG文件,但不知道用javascript解密JPG文件。 谁有更好的主意? 我正在苦苦挣扎4天。

byte[] ivBytes = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; String key = "1234567890123456789012345678901d"; AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes); SecretKeySpec newKey = new SecretKeySpec(key.getBytes("UTF-8"), "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(mode, newKey, ivSpec); InputStream input = null; OutputStream output = null; try { input = new BufferedInputStream(new FileInputStream(new File("/home/java/test/aaa.JPG"))); output = new BufferedOutputStream(new FileOutputStream(new File("/home/java/test/bbb.JPG"))); byte[] buffer = new byte[1024]; int read = -1; while((read = input.read(buffer)) != -1){ output.write(cipher.update(buffer, 0, read)); } output.write(cipher.doFinal()); } finally { if(output != null){ try { output.close(); } catch(IOException ie){ logger.info(ie.getMessage()); } } if(input != null){ try { input.close(); } catch(IOException ie){ logger.info(ie.getMessage()); } } } 

这是我到目前为止尝试过的代码。 我使用过CryptoJS而且Decrypt没有返回任何内容。

       JS Bin  article, aside, figure, footer, header, hgroup, menu, nav, section { display: block; }     your image Download  var a = $('.download'); var key = CryptoJS.enc.Hex.parse("1234567890123456789012345678901d"); var iv = CryptoJS.enc.Hex.parse("00000000000000000000000000000000"); function readURL(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { ///////// var decrypted = CryptoJS.AES.decrypt(e.target.result, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 } ).toString(CryptoJS.enc.Latin1); if(!/^data:/.test(decrypted)){ alert("Invalid pass phrase or file! Please try again."); return false; } a.attr('href', decrypted); a.attr('download', input.files[0].name.replace('.enc','')); }; //reader.readAsDataURL(input.files[0]); reader.readAsText(input.files[0]); } }    

您的密钥错误,Java(错误地)使用密钥的ASCII表示:

 String key = "1234567890123456789012345678901d"; ... SecretKeySpec newKey = new SecretKeySpec(key.getBytes("UTF-8"), "AES"); 

这导致AES-256的32字节密钥。 但是您的JavaScript使用密钥的hex解码:

 var key = CryptoJS.enc.Hex.parse("1234567890123456789012345678901d"); 

这导致AES-128的16字节密钥。

使用错误的键,您显然无法获得正确的结果。

因此,你必须对你的密钥进行编码,就像你在Java中使用IV或使用hex解码器(默认情况下不存在于Java中),或者你应该“修复”你的JavaScript以使用与Java相同的方式并使用ASCII编码关键字符串。

一般来说,密钥不应该是字符串。