利用JDK包 实现的DES加密/解密 和 字符串的md5计算

 

import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.security.*;
import java.security.spec.InvalidKeySpecException;

/**
 * 二行制转十六进制字串
 */
public static String byte2hex(byte[] b) {
    StringBuilder hs = new StringBuilder();
    String stmp;
    for (int n = 0; b != null && n < b.length; n++) {
        stmp = Integer.toHexString(b[n] & 0XFF);
        if (stmp.length() == 1)
            hs.append('0');
        hs.append(stmp);
    }
    return hs.toString().toUpperCase();
}

/**
 * 十六进制字串转二进制数组
 */
public static byte[] hex2byte(String hexStr) {
    byte[] b = hexStr.getBytes();
    if ((b.length % 2) != 0)
        throw new IllegalArgumentException();
    byte[] b2 = new byte[b.length / 2];
    for (int n = 0; n < b.length; n += 2) {
        String item = new String(b, n, 2);
        b2[n / 2] = (byte) Integer.parseInt(item, 16);
    }
    return b2;
}

/**
 * 计算md5码. 以MD5 32位输出
 */
public static byte[] getMD5Hash(byte[] data) throws Exception {
    MessageDigest md = MessageDigest.getInstance("MD5");
    md.update(data);
    return md.digest();
}

/**
 * @param keyBytes     key
 * @param dataBytes    要加密/解密的数据
 * @param algorithmDes 填充方式,
 * @param ivBytes      向量,可为空. 在DES_ECB填充模式中无法使用向量
 * @param mode         加密解密模式
 * @return 加密/解密后的byte数组
 */
public static byte[] des(byte[] keyBytes, byte[] dataBytes, String algorithmDes, byte[] ivBytes, int mode) {
    if (dataBytes == null) {
        return null;
    }
    try {
        assert keyBytes.length >= 8;
        DESKeySpec dks = new DESKeySpec(keyBytes);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        Key secretKey = keyFactory.generateSecret(dks);
        Cipher cipher = Cipher.getInstance(algorithmDes);
        if (ivBytes != null) {
            cipher.init(mode, secretKey, new IvParameterSpec(ivBytes));
        } else {
            cipher.init(mode, secretKey);
        }
        return cipher.doFinal(dataBytes);
    } catch (InvalidKeyException | NoSuchAlgorithmException | InvalidKeySpecException | IllegalBlockSizeException | BadPaddingException | InvalidAlgorithmParameterException | NoSuchPaddingException e) {
        e.printStackTrace();
        return null;
    }
}

转载于:https://my.oschina.net/CasparLi/blog/300077

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值