如何用Java进行3DES加密解密

public static String encryptKey(String mainKey,String plainKey){
		String encryptKey = "";
		try{
			Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); 
			String Algorithm = "DESede/ECB/NoPadding"; 
			byte[] hb = hex2byte(mainKey.getBytes());
			byte[] k = new byte[24];
			System.arraycopy(hb,0,k,0,16);
			System.arraycopy(hb,0,k,16,8);
			SecretKey deskey = new SecretKeySpec(k, Algorithm);
			Cipher c1 = Cipher.getInstance(Algorithm);
			c1.init(Cipher.ENCRYPT_MODE, deskey);
			encryptKey = byte2hex(c1.doFinal(hex2byte(plainKey.getBytes())));
		}catch(Exception e){
			e.printStackTrace();
		}
		return encryptKey;
	}
public static String byte2hex(byte[] b) {
		String hs = "";
		String stmp = "";
		for (int n = 0; n < b.length; n++) {
			stmp = Integer.toHexString(b[n] & 0xFF);
			if (stmp.length() == 1)
				hs += ("0" + stmp);
			else
				hs += stmp;
		}
		return hs.toUpperCase();
	}



3DES的加密密钥长度要求是24个字节,本例中因为给定的密钥只有16个字节,所以需要填补至24个字节。

其中"DESede/ECB/NoPadding",除此之外,3DES还支持"DESede/CBC/PKCS5Padding"模式。

此代码中使用了Bouncy Castle密码包,需要自行下载,下载地址:http://www.bouncycastle.org/latest_releases.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值