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")); }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM