java 3des PAd_通用的Java 3DES加密工具类,在线工具验证通过

/**

* 默认值:DESede/CBC/PKCS5Padding

* 经验证使用initKeyWithPadding方式生产密钥时,和网站:http://tool.chacuo.net/crypt3des,结果相同

*

* @version 1.0

* @since 1.0

*/

public abstract class DESCoder {

public static final String VI = "01234567";

/**

* 转换密钥

*

* @param key

* @return

* @throws Exception

*/

private static Key toKey(String key) throws Exception {

// DESKeySpec dks = new DESKeySpec(key.getBytes());

// SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");

// SecretKey secretKey = keyFactory.generateSecret(dks);

// 当使用其他对称加密算法时,如AES、Blowfish等算法时,用下述代码替换上述三行代码

SecretKey secretKey = new SecretKeySpec(key.getBytes(), "DESede");

return secretKey;

}

/**

* 解密

*

* @param data

* @param key

* @return

* @throws Exception

*/

public static byte[] decrypt(byte[] data, String key) throws Exception {

Key k = toKey(key);

Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");

IvParameterSpec ips = new IvParameterSpec(VI.getBytes());

cipher.init(Cipher.DECRYPT_MODE, k, ips);

return cipher.doFinal(data);

}

/**

* 生成密钥

*

* @return

* @throws Exception

*/

public static String initKey(String password) throws Exception {

return initKeyWithPadding(password);

}

/**

* 加密

*

* @param data

* @param key

* @return

* @throws Exception

*/

public static byte[] encrypt(byte[] data, String key) throws Exception {

Key k = toKey(key);

Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");

IvParameterSpec ips = new IvParameterSpec(VI.getBytes());

cipher.init(Cipher.ENCRYPT_MODE, k, ips);

return cipher.doFinal(data);

}

/**

* 通过MD5的方式,生成密钥

*

* @param password

* @return

* @throws Exception

*/

public static String initKeyWithMd5(String password) throws Exception {

return Md5Utils.hash(password).substring(0, 24);

}

/**

* 不足24位时,通过填充的方式生产密钥

* @param password

* @return

* @throws Exception

*/

public static String initKeyWithPadding(String password) throws Exception {

if (password.length() >= 24) {

return password;

} else {

byte[] bytes = password.getBytes();

byte[] result = new byte[24];

System.arraycopy(bytes,0,result,0,bytes.length);

return new String(result);

}

}

public static void main(String[] args) throws Exception {

String str = "ilkYC37ksDM=";

byte[] hh = Coder.decryptBASE64(str);

byte[] rr = DESCoder.decrypt(hh, DESCoder.initKey("123456"));

System.out.println(new String(rr));

byte[] uu = DESCoder.encrypt("hello".getBytes("UTF-8"), DESCoder.initKey("123456"));

System.out.println(Coder.encryptBASE64(uu));

}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值