2011-02-09 29 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来说是合法的。