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