[英]How to decrypt a file in javascript which is encrypted by JAVA with 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不返回任何東西。
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="./CryptoJS v3.1.2/rollups/aes.js"></script>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<style>
article, aside, figure, footer, header, hgroup,
menu, nav, section { display: block; }
</style>
</head>
<body>
<input type='file' onchange="readURL(this);" />
<img id="blah" src="#" alt="your image" />
<a class="download" href="">Download</a>
<script>
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]);
}
}
</script>
</body>
</html>
您的密鑰錯誤,Java(錯誤地)使用密鑰的ASCII表示形式:
String key = "1234567890123456789012345678901d";
...
SecretKeySpec newKey = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
這將為AES-256生成一個32字節的密鑰。 但是您的JavaScript使用密鑰的十六進制解碼:
var key = CryptoJS.enc.Hex.parse("1234567890123456789012345678901d");
這會導致AES-128使用16字節密鑰。
如果使用錯誤的鍵,您顯然將無法獲得正確的結果。
因此,您要么必須像在Java中進行IV一樣對密鑰進行編碼,要么使用十六進制解碼器(默認情況下在Java中不存在),或者您應該“修復” JavaScript以與Java相同,並使用ASCII編碼密鑰字符串。
通常,鍵不應為字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.