使用AES在Java中加密和解密

时间:2014-03-02 16:47:10

标签: java encryption aes

如何使用AES

在Java中EncryptDecrypt
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;


public class Encryption {
    public static void main(String args[]) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException{
                String t = "Testing";

                byte[] dataToSend = t.getBytes();
                byte[] key = new byte[16];

                Cipher c = Cipher.getInstance("AES");
                SecretKeySpec k = new SecretKeySpec(key, "AES");
                c.init(Cipher.ENCRYPT_MODE, k);
                byte[] encryptedData = c.doFinal(dataToSend);
                System.out.println(encryptedData);

                byte[] key2 = new byte[16];
                        byte[] encryptedData2 = encryptedData;

                        Cipher c2 = Cipher.getInstance("AES");
                        SecretKeySpec k2 =
                          new SecretKeySpec(key2, "AES");
                        c2.init(Cipher.DECRYPT_MODE, k2);
                        byte[] data = c.doFinal(encryptedData);
                        System.out.println(data);

    }
}

1 个答案:

答案 0 :(得分:0)

由于没有明确指出问题,我指出了明显的错误,假设加密的'Testing'应该在解密后打印'Testing'。

  1. AESsymmetric key算法,因此您必须使用相同的密钥进行加密和解密(k2根本不应该存在)
  2. c.doFinal加密数据没有多大意义,这应该引用您的密码DECRYPT_MODE - > c2
  3. 因此,改变:

    c2.init(Cipher.DECRYPT_MODE, k2);
    

    要:

    c2.init(Cipher.DECRYPT_MODE, k);
    

    并改变:

    byte[] data = c.doFinal(encryptedData);
    

    要:

    byte[] data = c2.doFinal(encryptedData);
    

    打印最终结果:

    变化:

    System.out.println(data);
    

    要:

    System.out.println(new String(data));