`
wangking717
  • 浏览: 257635 次
  • 性别: Icon_minigender_2
  • 来自: 成都
社区版块
存档分类
最新评论

JAVA AES加密解决方案

阅读更多
 写道
此次加密基于AES-128 CBC PKCS5填充模式。密钥为长度64的hex string,将其转为32-byte key,前8 bytes和后8 bytes组合为key,剩下中间的为IV。
如密钥:112b1ea14ae0ac4c081c26b4974b03f8c41d40cea3418eba6c0203404cb470bf
那么可划分为112b1ea14ae0ac4c |||| 081c26b4974b03f8c41d40cea3418eba ||| 6c0203404cb470bf
注:一个byte对应2个hex string

 

源代码:

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AESEncryptor {

	private static String AES_HEX = "112b1ea14ae0ac4c081c26b4974b03f8c41d40cea3418eba6c0203404cb470bf";
	private Cipher cipher;
	private IvParameterSpec dps;
	private SecretKeySpec skeySpec;
	
	public AESEncryptor() throws Exception{
		byte[] passkey = hex2Bin(AES_HEX);
		byte[] key = getAESKey(passkey);
		byte[] iv = getAESIV(passkey);
		dps = new IvParameterSpec(iv);
		skeySpec = new SecretKeySpec(key, "AES");
		cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
	}
	
	private byte[] getAESIV(byte[] keyRaw) throws Exception {	//获得32 byte数组中的一部分作为KEY
		byte[] iv = new byte[16];
		System.arraycopy(keyRaw, 8, iv, 0, 16);
		return iv;
	}

	private byte[] getAESKey(byte[] keyRaw) throws Exception {	//获得32 byte数组中的一部分作为KEY
		byte[] key = new byte[16];
		System.arraycopy(keyRaw, 0, key, 0, 8);
		System.arraycopy(keyRaw, 24, key, 8, 8);
		return key;
	}

	public String encrypt(String command) throws Exception {
		
		cipher.init(Cipher.ENCRYPT_MODE, skeySpec, dps);
		byte[] buf = cipher.doFinal(command.getBytes());

		return this.byte2hexString(buf);
	}

	public String decrypt(String sSrc) throws Exception {

		cipher.init(Cipher.DECRYPT_MODE, skeySpec, dps);
		return new String(cipher.doFinal(hex2Bin(sSrc)));

	}

	private byte[] hex2Bin(String src) {
		if (src.length() < 1)
			return null;
		byte[] encrypted = new byte[src.length() / 2];
		for (int i = 0; i < src.length() / 2; i++) {
			int high = Integer.parseInt(src.substring(i * 2, i * 2 + 1), 16);
			int low = Integer.parseInt(src.substring(i * 2 + 1, i * 2 + 2), 16);

			encrypted[i] = (byte) (high * 16 + low);
		}
		return encrypted;
	}

	private String byte2hexString(byte buf[]) {
		StringBuffer strbuf = new StringBuffer(buf.length * 2);
		int i;

		for (i = 0; i < buf.length; i++) {
			if (((int) buf[i] & 0xff) < 0x10)
				strbuf.append("0");

			strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
		}

		return strbuf.toString();
	}

	public static void main(String[] args) {
		AESEncryptor aes = null;
		try {
			aes = new AESEncryptor();
			String para = aes.encrypt("password=testpswd");
			System.out.println(para);
			String s = aes.decrypt("29694e1985a631fade0d92fca230f75f2724e6c7fc96d15cdcdef787012ad803");
			System.out.println(s);
			System.out.println(aes.encrypt("password=testpswd"));
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics