使用填充密码进行解密时,对输入长度的建议必须是16的倍数

时间:2014-08-31 10:10:10

标签: java encryption cryptography client-server aes

我正在研究java客户端服务器aes加密哪个服务器加密和客户端解密。但是我有填充错误可能为byte []和string..i无法解决它。任何人都可以告诉我要改变什么来解决加密和解密问题?

SERVER

    public void run(){
    try {
        String key1 = "1234567812345678"; 
        byte[] key2 = key1.getBytes();
        SecretKeySpec secret = new SecretKeySpec(key2, "AES");
        String msg = "Singapore Malaysia Japan India";
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");        
        cipher.init(Cipher.ENCRYPT_MODE, secret);
        byte[] encrypted = cipher.doFinal(msg.getBytes());

        in = new DataInputStream(incoming.getInputStream());
        out = new DataOutputStream(incoming.getOutputStream());


        boolean done = false;
        String str="";
        out.writeUTF("Connected!\n");
        out.flush();
        while (!done){
            out.writeUTF(">");
            out.flush();
            str = in.readUTF();
            System.out.println(in+":"+str);
            if (str == null)
                done = true;
            else{
                System.out.println("Sending Ciphertext : " + new String(encrypted));
                out.writeUTF(new String(encrypted));
                out.flush();

客户端

String str = "";
    String str2 = "";
    DataOutputStream out;
    DataInputStream in;

    try {
        Socket t = new Socket("127.0.0.1", 9003);
        in = new DataInputStream(t.getInputStream());
        out = new DataOutputStream(t.getOutputStream());
        BufferedReader br = new BufferedReader (new InputStreamReader(System.in));

        boolean more = true;
        System.out.println(in.readUTF());   

        while (more) {
            str = in.readUTF();
            System.out.print(str);
            str2 = br.readLine();
            out.writeUTF(str2);
            out.flush();
            str = in.readUTF();

            System.out.println("Encrypted Info: " + str);

            try {
                String key1 = "1234567812345678"; 
                byte[] key2 = key1.getBytes();
                SecretKeySpec secret = new SecretKeySpec(key2, "AES");

                Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");        

                cipher.init(Cipher.DECRYPT_MODE, secret);
                byte[] decrypted = cipher.doFinal(str.getBytes());
                System.out.println("Decrypted Info: " + new String(decrypted));

            }

1 个答案:

答案 0 :(得分:2)

所有字符串都可以转换为字节,但不一定是相反的情况;字节并不总是有效的字符串。

因此,您需要做的是以二进制形式传输密文,或者您需要使用以下方法将字节专门编码为字符。 base 64编码。