2014-06-09 63 views
-1

我不確定我是否可以提出這樣的問題。如果這不適合,我表示歉意。如何解密用Java代碼加密的字符串?

我需要解密一些使用以下Java代碼加密的數據。我安裝了aes gem並掙扎了2個小時,但無法完成。

我知道紅寶石,但我的Java知識是有限的。誰給了我這個代碼的另一個人不知道紅寶石。所以我需要你的幫助。我只需要一個解密功能。

我出於安全原因更改了密鑰。

import javax.crypto.Cipher;   
import javax.crypto.spec.SecretKeySpec;   

import org.apache.commons.codec.DecoderException;   
import org.apache.commons.codec.binary.Hex;   

import sun.misc.BASE64Decoder;   
import sun.misc.BASE64Encoder;   


public class AESTest {   
    private static String sKeyString = "29c4e20e74dce74f44464e814529203a";  
    private static SecretKeySpec skeySpec = null;  

    static {   
     try { 
      skeySpec = new SecretKeySpec(Hex.decodeHex(sKeyString.toCharArray()), "AES"); 
     } catch (DecoderException e) { 
      e.printStackTrace(); 
     } 
    }  

    public static String encode(String message) {  
     String result = ""; 

     try { 
      Cipher cipher = Cipher.getInstance("AES"); 
      cipher.init(Cipher.ENCRYPT_MODE, skeySpec); 
      byte[] encrypted = cipher.doFinal(message.getBytes("UTF-8")); 
      result = (new BASE64Encoder()).encode(encrypted); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

     return result; 
    }  

    public static String decode(String message){   
     String result = ""; 
     try { 
      Cipher cipher = Cipher.getInstance("AES"); 
      cipher.init(Cipher.DECRYPT_MODE, skeySpec); 
      byte[] encrypted = (new BASE64Decoder()).decodeBuffer(message); 
      byte[] original = cipher.doFinal(encrypted); 
      result = new String(original,"UTF-8"); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

     return result; 
    }  

    public static void main(String[] args) {   
     String message = "SOME TEST"; 
     System.out.println("message : "+message); 
     String encodeString = encode(message); 
     System.out.println("encrypted string: " + encodeString);  
     String original = decode(encodeString); 
     System.out.println("Original string: " + original); 
    }  
}   

謝謝。

Sam

+2

您有解碼功能 – James

+0

使用解碼(字符串消息)函數時是否出現錯誤? – Dinal

+1

如果您顯示了迄今爲止的努力並且/或者在遇到問題時進行了解釋,問題就會得到改善。 「掙扎2小時但不能做」這句話涵蓋了太多可能出錯的事情。也許你只需要稍微修改一下你的嘗試? –

回答

0

sKeyString變量具有十六進制鍵值。

要解碼你首先需要Base64解碼來獲得帶有加密信息的字節數組。 然後,您可能需要十六進制解碼密鑰才能獲取密鑰的字節。這很簡單,sKeyString中的每2個字符都是一個字節。然後,只需使用AES解密器使用該密鑰解密消息字節即可。

相關問題