2012-07-13 88 views
0

我想從Java(Android)發送數據到Node.js應用程序,除了加密不工作和Node.js沒有正確解密,我真的不知道我在做什麼。加密和解密數據通過傳輸通過Java到Node.js

的Java:

    // Encrypt 
        byte[] input = jo.toString().getBytes("UTF-8"); 

        MessageDigest md = MessageDigest.getInstance("MD5"); 
        byte[] thedigest = md.digest(ENCRYPTION_KEY.getBytes("UTF-8")); 
        SecretKeySpec skc = new SecretKeySpec(thedigest, "AES/ECB/PKCS5Padding"); 
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); 
        cipher.init(Cipher.ENCRYPT_MODE, skc); 

        byte[] cipherText = new byte[cipher.getOutputSize(input.length)]; 
        int ctLength = cipher.update(input, 0, input.length, cipherText, 0); 
        ctLength += cipher.doFinal(cipherText, ctLength); 
        String query = Base64.encodeToString(cipherText, Base64.DEFAULT); 

query然後被髮送到我們的服務器和joJSONObject

及以上的節點,我做:

 var decipher = crypto.createDecipher('aes-128-ecb', encryption_key); 
     console.log("System: " + new Buffer(fullBuffer, "base64").toString("binary")); 

     chunks = [] 
     chunks.push(decipher.update(new Buffer(fullBuffer, "base64").toString("binary") , 'hex', 'utf-8')); 
     chunks.push(decipher.final('utf-8')); 
     var txt = chunks.join(""); 

     console.log("System: " + txt); 
     js = JSON.parse(txt); 
     console.log("System: " + js); 

而且fullBuffer是收到正確傳輸的POST數據

+0

那麼,什麼問題? – 2012-07-13 19:57:52

+0

如何在Java中正確加密數據,然後使用AES在Node.js中對其進行解密 – 2012-07-13 19:59:03

+0

我看到一個可接受的答案Joe,但實際解決了什麼問題? – 2012-07-15 20:58:32

回答

2

加密和身份驗證對調試很殘酷,因爲您犯的任何錯誤都會導致整個輸出隨機化。建議:

  1. 切換到像Base64或gzip這樣的非加密轉換,以便您可以看到您的輸出看起來像什麼。
  2. 試着找出哪一半是壞的。捕獲你的服務器輸出並用openssl或python解碼。用其中一種生成一些好的輸入並將其填入客戶端。
  3. CBC比ECB更安全。
  4. 如果這些都沒有幫助,請進入低級密碼和解密,並確保密鑰和密文在內容和長度上完全匹配,並且長時間難以眯眼算法選擇。
+0

謝謝,我不能使用CBC沒有它打破。代碼:https://gist.github.com/3111592 – 2012-07-14 14:31:34