java实现DESede加解密

上篇中说了在迁移.net项目到java平台过程中,遇到各种问题,其中最大的莫过于各种加解密算法的跨平台实现。那个.net项目中用到MD5、DESede、AES、RSA,我也是醉了,这坑够大。

不多说,奉上代码。


import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

public class DESedeUtil {

	/**
	 * 密钥算法
	 */
	private static final String KEY_ALGORITHM = "DESede";
	
	/**
	 * 加密/解密算法 / 工作模式 / 填充方式
	 * Java 6支持PKCS5Padding填充方式
	 * Bouncy Castle支持PKCS7Padding填充方式
	 */
	private static final String CIPHER_ALGORITHM = "DESede/ECB/PKCS5Padding";
	
	/**
	 * 生成密钥
	 * @return	密钥
	 * @throws Exception
	 */
	public static String generateKey() throws Exception {
		//实例化密钥生成器
		KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
		//DESede 要求密钥长度为 112位或168位
		kg.init(168);
		//生成密钥
		SecretKey secretKey = kg.generateKey();
		//获得密钥的字符串形式
		return Base64.encodeBase64String(secretKey.getEncoded());
	}
	
	/**
	 * des加密
	 * @param source	源字符串
	 * @param key	密钥
	 * @return	加密后的密文
	 * @throws Exception
	 */
    public static String encrypt(String source, String key) throws Exception {
        byte[] sourceBytes = source.getBytes("UTF-8");
    	byte[] keyBytes = Base64.decodeBase64(key);
    	Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
    	cipher.init(Cipher.ENCRYPT_MODE,new SecretKeySpec(keyBytes, KEY_ALGORITHM));
    	byte[] decrypted = cipher.doFinal(sourceBytes);
    	return Base64.encodeBase64String(decrypted);
    }
    
    /**
     * des解密
     * @param encryptStr	密文
     * @param key	密钥
     * @return	源字符串
     * @throws Exception
     */
    public static String decrypt(String encryptStr, String key) throws Exception {
    	byte[] sourceBytes = Base64.decodeBase64(encryptStr);
		byte[] keyBytes = Base64.decodeBase64(key);
    	Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
    	cipher.init(Cipher.DECRYPT_MODE,new SecretKeySpec(keyBytes, KEY_ALGORITHM));
    	byte[] decoded = cipher.doFinal(sourceBytes);
    	return new String(decoded, "UTF-8");
    }
    
}


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值