commons-codec-1.8.jar的加密

package com.test;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.log4j.Logger;

public class EncryptionUtil {
	static String baseKey = "@7h$*0m#+-^j59z=";
	static String AES = "AES";
	private static final Logger logger = Logger.getLogger(EncryptionUtil.class);

	private static byte[] getUseKeyBytes(String key) {
		if (key == null)
			key = "";
		else if (key.length() > 8) {
			key = key.substring(0, 8);
		}
		byte[] secondKeyBytes = key.getBytes();
		byte[] baseKeyBytes = baseKey.substring(0, 16 - key.length())
				.getBytes();
		byte[] useKeyBytes = new byte[secondKeyBytes.length
				+ baseKeyBytes.length];
		System.arraycopy(secondKeyBytes, 0, useKeyBytes, 0,
				secondKeyBytes.length);
		System.arraycopy(baseKeyBytes, 0, useKeyBytes, secondKeyBytes.length,
				baseKeyBytes.length);
		return useKeyBytes;
	}

	public static String encrypt(String str, String key) throws Exception {
		return new String(new Hex().encode(cipher(str.getBytes(), key, 1)));
	}

	public static String decrypt(String str, String key) throws Exception {
		return new String(cipher(new Hex().decode(str.getBytes()), key, 2));
	}

	private static byte[] cipher(byte[] bytes, String key, int cipherMode)
			throws Exception {
		byte[] useKeyBytes = getUseKeyBytes(key);

		SecretKeySpec skeySpec = new SecretKeySpec(useKeyBytes, AES);

		Cipher cipher = Cipher.getInstance(AES);

		cipher.init(cipherMode, skeySpec);

		return cipher.doFinal(bytes);
	}

	public static void main(String[] args) throws Exception {
		String key = "12345";
		String message = "cochin";
		String encrypted = encrypt(message, key);
		System.out.println(encrypted);
		logger.info(encrypted);

		String decrypted = decrypt(encrypted, key);
		logger.info(decrypted);
		
		String Str=DigestUtils.md5Hex("12345");//加密
		System.out.println(Str);
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值