本文共 3994 字,大约阅读时间需要 13 分钟。
package com.lazycat.secure.aes; import .nio.charset.Charset; import java.security.NoSuchAlgorithmException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import javax.crypto.Cipher; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.SecretKeySpec; public class AESCoder { public static int count = 1000000; public static CountDownLatch latch =new CountDownLatch(count); public static void main(String[] args)throws Exception { ExecutorService pool = Executors.newFixedThreadPool(200); final byte[] payload = "{\"msg\":{\"content\":{\"text\":\"JJH\",\"tplId\":0},\"from\":{\"name\":\"10000213\",\"id\":1,\"type\":0},\"to\":{\"name\":\"10095812\",\"id\":10000213,\"type\":0},\"time\":0,\"txid\":0,\"subtype\":1},\"type\":\"chat\"}".getBytes(Charset.forName("utf-8")); final String secureKey ="BBmFdTFVgAjgHNwRkWWRcOFFiBzAANFU9DmMAP1JpBmc."; long start = System.currentTimeMillis(); for(int i = 0 ; i <count ; i++){ pool.execute(new Runnable() { public void run() { AESCoder coder = new AESCoder(); byte[] enret =null; try { enret = coder.encrypt(payload,secureKey); byte[] deret = coder.decrypt(enret, secureKey); System.out.println(new String(deret,"utf-8")); } catch (Exception e) { e.printStackTrace(); } latch.countDown(); } }); } latch.await(); System.out.println(System.currentTimeMillis() - start); pool.shutdown(); } private byte[] encrypt(byte[] payload,String securekey)throws Exception{ byte[] enCodeFormat = securekey.substring(0, 16).getBytes(); SecretKeySpec key = newSecretKeySpec(enCodeFormat,"AES"); Cipher cipher = CliperInstance.getInstance();//创建密码器 //Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key);//初始化 byte[] result = cipher.doFinal(payload); return result; } public byte[] decrypt(byte[] buffer,StringsecureKey)throws Exception{ byte[] enCodeFormat = secureKey.substring(0,16).getBytes(); SecretKeySpec key = newSecretKeySpec(enCodeFormat,"AES"); //Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//创建密码器 Cipher cipher = CliperInstance.getInstance(); cipher.init(Cipher.DECRYPT_MODE, key);//初始化 byte[] result = cipher.doFinal(buffer); return result; } } class CliperInstance { private static ThreadLocal<Cipher> cipherTL =new ThreadLocal<Cipher>(){ @Override protected Cipher initialValue() { try { return Cipher.getInstance("AES/ECB/PKCS5Padding"); }catch(Exception e){ return null; } } }; public static CiphergetInstance() throws NoSuchAlgorithmException, NoSuchPaddingException{ returncipherTL.get(); } } |
转载地址:http://jbntx.baihongyu.com/