1. 程式人生 > 實用技巧 >keyGenerator和Cipher類實現AES對稱加密

keyGenerator和Cipher類實現AES對稱加密

public static void symmetricEncrypt(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException,
            IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException, InvalidKeyException {
        //
        // check args and get plaintext
        if (args.length != 1) {
            System.err.println(
"Usage: java PrivateExample text"); System.exit(1); } byte[] plainText = args[0].getBytes("UTF8"); // // get a DES private key System.out.println("\nStart generating DES key"); KeyGenerator keyGen = KeyGenerator.getInstance("AES"); keyGen.init(
256);//128,192,256三者選一 Key key = keyGen.generateKey(); System.out.println("Finish generating DES key"); // save key byte[] encoded = key.getEncoded(); Arrays.asList(encoded).forEach(System.out::println); // // get a DES cipher object and print the provider
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); System.out.println("\n" + cipher.getProvider().getInfo()); // // encrypt using the key and the plaintext System.out.println("\nStart encryption"); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] cipherText = cipher.doFinal(plainText); System.out.println("Finish encryption: "); System.out.println(new String(cipherText, "UTF8")); byte[] dencoded = encoded;//模擬取出私鑰,然後解密加密後的內容 Key k = new SecretKeySpec(dencoded,"AES"); // decrypt the ciphertext using the same key System.out.println("\nStart decryption"); Cipher dcipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); dcipher.init(Cipher.DECRYPT_MODE, k); byte[] newPlainText = dcipher.doFinal(cipherText); System.out.println("Finish decryption: "); System.out.println(new String(newPlainText, "UTF8")); }