0

このチュートリアルhttp://www.java2s.com/Code/Android/Security/AESEncryption.htmに従って Java でプログラムを作成しました が、「javax.crypto.IllegalBlockSizeException: Input length must be multiple ofパディングされた暗号で復号化する場合は 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 に答える