2011-02-09 50 views
0
public String Encryption(String toEncrypt) throws Exception 
{ 
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); 
    EditText et = (EditText) findViewById(R.id.entry); 
    byte[] input = toEncrypt.getBytes(); 
    byte[] keyBytes = "hello".getBytes(); 
    // et.setText("in encryption"); 
    SecretKeySpec key = new SecretKeySpec(keyBytes, "AES"); 
    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC"); 
    // et.setText("in encryption"); 

    cipher.init(Cipher.ENCRYPT_MODE, key); 

    et.setText("in encryption"); 
    byte[] cipherText = new byte[cipher.getOutputSize(input.length)]; 
    int ctLength = cipher.update(input, 0, input.length, cipherText, 0); 
    ctLength += cipher.doFinal(cipherText, ctLength); 
    // et.setText("in encryption"); 
    // return "abc"; 
    return cipherText.toString(); 

從我加粗的代碼行(cipher.init(Cipher.ENCRYPT_MODE, key);)程序不工作 - 我得到一個異常。這條線有什麼問題?我試圖基本上加密一個字符串,並用這個函數返回它。這個在android中的加密代碼有什麼問題?

+1

嘗試重新格式化,並且還包含異常的內容。否則,真的很難回答你的問題。 – 2011-02-09 23:53:57

回答

1

您的密鑰長度必須爲16,24或32個字節。沒有其他尺寸對於AES來說是合法的。