0

我已经按照本教程http://www.java2s.com/Code/Android/Security/AESEncryption.htm在 java 中编写了我的程序 但我得到一个异常,即“javax.crypto.IllegalBlockSizeException:输入长度必须是16 使用填充密码解密时"

有谁能够帮我?

public class utils {

public static String encrypt(String message,String secretPhrase){
    try{
        MessageDigest mdig=MessageDigest.getInstance("MD5");
        byte[] digestedBytes=mdig.digest(secretPhrase.getBytes("UTF-8"));
        SecretKeySpec keySpec=new SecretKeySpec(digestedBytes,"AES");

        Cipher cipher=Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, keySpec);
        byte[] encryptedBytes=cipher.doFinal(message.getBytes("UTF-8"));

        return new String(encryptedBytes,"UTF-8");
    }catch(Exception exc){
        return null;
    }
}

public static String decrypt(String message,String secretPhrase){
    try{
        MessageDigest mdig=MessageDigest.getInstance("MD5");
        byte[] digestedBytes=mdig.digest(secretPhrase.getBytes("UTF-8"));
        SecretKeySpec keySpec=new SecretKeySpec(digestedBytes,"AES");

        Cipher cipher=Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, keySpec);
        byte[] encryptedBytes=cipher.doFinal(message.getBytes("UTF-8"));

        return new String(encryptedBytes,"UTF-8");
    }catch(Exception exc){
        return null;
    }
}

}

4

1 回答 1

0

试试这个,

public String encrypt(String str) {
    try {
        // Encode the string into bytes using utf-8
        byte[] utf8 = str.getBytes("UTF8");

        // Encrypt
        byte[] enc = ecipher.doFinal(utf8);

        // Encode bytes to base64 to get a string
        return new sun.misc.BASE64Encoder().encode(enc);
    }  catch (Exception e) {
    }
    return null;
}

public String decrypt(String str) {
    try {
        // Decode base64 to get bytes
        byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);

        // Decrypt
        byte[] utf8 = dcipher.doFinal(dec);

        // Decode using utf-8
        return new String(utf8, "UTF8");
    }  catch (Exception e) {
    }
    return null;
}

使用它的例子

try {
    // Generate a temporary key. In practice, you would save this key.
    // See also Encrypting with DES Using a Pass Phrase.
    SecretKey key = KeyGenerator.getInstance("DES").generateKey();

    // Create encrypter/decrypter class
    DesEncrypter encrypter = new DesEncrypter(key);

    // Encrypt
    String encrypted = encrypter.encrypt("Don't tell anybody!");

    // Decrypt
    String decrypted = encrypter.decrypt(encrypted);
} catch (Exception e) {
}
于 2013-02-07T13:14:30.270 回答