2017-08-30 160 views
0

enter image description here我想用AES加密Java中的Java文件,但我不知道如何用JavaScript解密JPG文件。任何人有更好的主意? 这是我的Java代码。如何解密CryptoJS中的文件,通过JAVA用AES加密

`private static void EncFile(File srcFile, File encFile) throws Exception 
     { 
      if(!srcFile.exists()){ 
      System.out.println("source file not exixt"); 
      return; 
     }// 
     if(!encFile.exists()){ 
      System.out.println("encrypt file created"); 
      encFile.createNewFile(); 
     } 

    byte[] bytes = new byte[1024*8]; 
    String key = "1234567812345678"; 
    String iv = "1234567812345678"; 
    Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); 
    int blockSize = cipher.getBlockSize(); 
    SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES"); 
    IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes()); 
    cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec); 


    InputStream fis = new FileInputStream(srcFile); 
    // CipherInputStream cin = new CipherInputStream(fis, cipher); 
    OutputStream fos = new FileOutputStream(encFile); 

    while ((dataOfFile = fis.read(bytes)) >0) { 


     byte[] encrypted = cipher.doFinal(bytes); 
     fos.write(encrypted,0,dataOfFile); 
    } 

    fis.close(); 
    fos.flush(); 
    fos.close(); 
}` 

这个我javascipt的代码,我已经使用CryptoJS和解密确实

var key = CryptoJS.enc.Latin1.parse('1234567812345678'); 
    var iv = CryptoJS.enc.Latin1.parse('1234567812345678'); 

var url = "http://192.168.0.103/show3d_test/test/CR4/E1234.png"; 

var xhr = new XMLHttpRequest(); 
xhr.open("GET",url,true); 
xhr.responseType = "arraybuffer"; 
xhr.onload = function() { 
    if(xhr.readyState ==4){ 
    if (xhr.status == 200){ 
     process(xhr.response,key); 
    } 
    } 
} 
xhr.send(); 


function process(buffer,key) { 
var view = new Uint8Array(buffer); 
var contentWA = CryptoJS.enc.u8array.parse(view); 
var dcBase64String = contentWA.toString(CryptoJS.enc.Base64); 
var decrypted = CryptoJS.AES.decrypt(dcBase64String,key, 
{iv:iv,mode:CryptoJS.mode.CBC,padding:CryptoJS.pad.NoPadding}); 

var d64 = decrypted.toString(CryptoJS.enc.Base64); 


var img = new Image; 
img.src = "data:image/png;base64,"+d64; 
document.body.append(img); 
} ` 

任何人都知道该怎么做?我已经看到了很多关于CryptoJS的例子 - Java加密/解密,但其中大多数使用硬编码的IV /密钥,或者只是从cryptoJS端向IV端发送IV /密钥。我拥有的只是一个密码,就像本网站所做的一样!

+0

当我解密这张照片时,我发现我只能解密成功的部分。该图片仅显示了显示的一部分 – sunday

回答

0

不确定确切的问题是什么,但这应该有所帮助。

IV的一个通用和安全的方法是创建一个带有CSPRNG(随机字节)的数据,并将加密数据与IV作为前缀,以便它可用于解密。 IV不需要保密。

使用“AES/CBC/NoPadding”时,输入必须是块大小的精确倍数(AES为16字节)。通常指定PKCS#7(PKCS#5)填充,因此对要加密的数据长度没有限制。