这个加密代码在android中出了什么问题?

时间:2011-02-09 23:39:19

标签: android encryption

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);)程序不起作用 - 我得到一个例外。这条线有什么问题?我试图基本上加密一个字符串并使用此函数返回它。

1 个答案:

答案 0 :(得分:1)

您的密钥长度必须为16,24或32字节。没有其他尺寸适合AES。