1

我正在尝试开发一个简单的加密/解密程序。我遇到的问题是当我尝试解密加密的消息时,我收到一条错误消息,指出使用密码解密时输入长度必须是 16 的倍数。我在某处读到加密消息可能需要在将其转换为字符串之前进行编码。我不知道该怎么做?或者,如果有另一种方法,有人可以帮助我吗?

import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;


public class Cryption {
    public static void cryption(String[] args, String message) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException {
        byte[] encodedKey = "ADBSJHJS12547896".getBytes();
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        Key aesKey = keyGen.generateKey();

        System.out.println("CheckType: "+ Global.checkType);
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, aesKey);
        byte[] input = Global.message.getBytes();

        // Check if clicked Encrypted
        if(Global.checkType==true) {
            // Encrypt
            byte[] messageEncrypted = cipher.doFinal(input);
            System.out.println("Encrypted Text: " + messageEncrypted);
            Global.encValue = messageEncrypted.toString();
        }

        // Check if clicked Decrypted
        if(Global.checkType==false) {
            //String mes = message;
            System.out.println(Global.message);
            System.out.println("Char lenght " + Global.message.length());
            byte[] mesByte = Global.message.getBytes();


            // Decrypt
            cipher.init(Cipher.DECRYPT_MODE, aesKey);
            byte[] messageDecrypted = cipher.doFinal(mesByte);
            System.out.println("Text Decrypted: " + new String(messageDecrypted));
        }
    }

}
4

2 回答 2

1
Global.encValue = messageEncrypted.toString();

这是完全错误的,因为它只是调用 byte[].toString(),它没有给你内容,只是一个带有类名和哈希码的东西。这在语义上也是错误的,因为 String 首先不是二进制数据的容器。不要将加密文本转换为字符串。使用 API 提供的 byte[] 数组。

于 2012-02-28T03:55:52.450 回答
0

看看http://docs.oracle.com/javase/tutorial/i18n/text/string.html

这可能意味着它不知道它是 ASCII 还是 UTF8 或其他一些字节编码......

于 2012-02-28T03:38:26.890 回答