展开
拓展 关闭
订阅号推广码
GitHub
视频
公告栏 关闭

加解密:BouncyCastle、Hmac算法

  • BouncyCastle加密
# 导入bcprov-jdk15on-xxx.jar

public class Main {
    public static void main(String[] args) throws Exception {
        // 注册BouncyCastle:
        Security.addProvider(new BouncyCastleProvider());
        // 按名称正常调用:
        MessageDigest md = MessageDigest.getInstance("RipeMD160");
        md.update("HelloWorld".getBytes("UTF-8"));
        byte[] result = md.digest();
        System.out.println(new BigInteger(1, result).toString(16));
    }
}
# 控制台
ecabeaa2eb986c85e6a6ea2c22b248ab6916de35
  • Hmac算法加密
通过名称HmacMD5获取KeyGenerator实例;
通过KeyGenerator创建一个SecretKey实例;
通过名称HmacMD5获取Mac实例;
用SecretKey初始化Mac实例;
对Mac实例反复调用update(byte[])输入数据;
调用Mac实例的doFinal()获取最终的哈希值。

public class Test1 {
    public static void main(String[] args) throws Exception {
        KeyGenerator keyGen = KeyGenerator.getInstance("HmacMD5");
        SecretKey key = keyGen.generateKey();
        // 打印随机生成的key:
        byte[] skey = key.getEncoded();
        System.out.println("->byte" + Arrays.toString(skey));
        System.out.println("hkey-->" + new BigInteger(1, skey).toString(16));
        Mac mac = Mac.getInstance("HmacMD5");
        mac.init(key);
        mac.update("HelloWorld".getBytes("UTF-8"));
        byte[] result = mac.doFinal();
        System.out.println("md--->" + new BigInteger(1, result).toString(16));
    }
}
# 控制台
->byte[-38, 81, 119, -9, 41, -17, 92, 104, 11, 15, -13, -102, -34, 110, 2, -52, 26, -119, 14, 6, -109, 97, 94, 5, -127, 92, 51, 23, 90, -106, 16, -111, -8, -79, 82, -96, -57, 82, 64, -60, -33, 1, -17, 68, 8, 53, -75, -29, 32, -56, 98, 40, 121, -102, -28, -116, -85, -9, -9, -43, -61, -46, -88, -27]
hkey-->da5177f729ef5c680b0ff39ade6e02cc1a890e0693615e05815c33175a961091f8b152a0c75240c4df01ef440835b5e320c86228799ae48cabf7f7d5c3d2a8e5
md--->37c72b0de6d848dfdf1b93badb06cef

# 验证
public class Test2 {
    public static void main(String[] args) throws Exception {
        byte[] hkey = new byte[] {-38, 81, 119, -9, 41, -17, 92, 104, 11, 15, -13, -102, -34, 110, 2, -52, 26, -119, 14, 6, -109, 97, 94, 5, -127, 92, 51, 23, 90, -106, 16, -111, -8, -79, 82, -96, -57, 82, 64, -60, -33, 1, -17, 68, 8, 53, -75, -29, 32, -56, 98, 40, 121, -102, -28, -116, -85, -9, -9, -43, -61, -46, -88, -27};

        SecretKey key = new SecretKeySpec(hkey, "HmacMD5");
        Mac mac = Mac.getInstance("HmacMD5");
        mac.init(key);
        mac.update("HelloWorld".getBytes("UTF-8"));
        byte[] result = mac.doFinal();
        System.out.println("md--->" + new BigInteger(1, result).toString(16));
        //System.out.println(Arrays.toString(result));
    }
}
# 控制条
md--->37c72b0de6d848dfdf1b93badb06cef
  • 案例一
# 导入依赖
    <dependencies>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.11</version>
        </dependency>
    </dependencies>

# 编写工具类
import java.nio.charset.Charset;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class JdkHmacUtils {

    // 获取 HmacMD5 Key
    public static byte[] getHmacMd5Key() {
        return getHmacKey("HmacMD5");
    }

    // 获取 HmacSHA256
    public static byte[] getHmacSha256Key() {
        return getHmacKey("HmacSHA256");
    }

    // 获取 HmacSHA512
    public static byte[] getHmacSha512Key() {
        return getHmacKey("HmacSHA512");
    }

    // 获取 HMAC Key
    public static byte[] getHmacKey(String type) {
        try {
            // 1、创建密钥生成器
            KeyGenerator keyGenerator = KeyGenerator.getInstance(type);
            // 2、产生密钥
            SecretKey secretKey = keyGenerator.generateKey();
            // 3、获取密钥
            byte[] key = secretKey.getEncoded();
            return key;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // HMAC MD5 加密
    public static String encryptHmacMD5(byte[] data, byte[] key) {
        return encryptHmac(data, key, "HmacMD5");
    }

    // HMAC SHA256 加密
    public static String encryptHmacSHA256(byte[] data, byte[] key) {
        return encryptHmac(data, key, "HmacSHA256");
    }

    // HMAC SHA521 加密
    public static String encryptHmacSHA512(byte[] data, byte[] key) {
        return encryptHmac(data, key, "HmacSHA512");
    }

    // 基础MAC 算法
    public static String encryptHmac(byte[] data, byte[] key, String type) {
        try {
            // 1、还原密钥
            SecretKey secretKey = new SecretKeySpec(key, type);
            // 2、创建MAC对象
            Mac mac = Mac.getInstance(type);
            // 3、设置密钥
            mac.init(secretKey);
            // 4、数据加密
            byte[] bytes = mac.doFinal(data);
            // 5、生成数据
            String rs = encodeHex(bytes);
            return rs;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // 数据准16进制编码
    public static String encodeHex(final byte[] data) {
        return encodeHex(data, true);
    }

    // 数据转16进制编码
    public static String encodeHex(final byte[] data, final boolean toLowerCase) {
        final char[] DIGITS_LOWER = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
        final char[] DIGITS_UPPER = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
        final char[] toDigits = toLowerCase ? DIGITS_LOWER : DIGITS_UPPER;
        final int l = data.length;
        final char[] out = new char[l << 1];
        // two characters form the hex value.
        for (int i = 0, j = 0; i < l; i++) {
            out[j++] = toDigits[(0xF0 & data[i]) >>> 4];
            out[j++] = toDigits[0x0F & data[i]];
        }
        return new String(out);
    }
}

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.HmacAlgorithms;
import org.apache.commons.codec.digest.HmacUtils;

public class CCHmacUtils {

    // 获取 HmacMD5 Key
    public static byte[] getHmacMd5Key() {
        return getHmacKey("HmacMD5");
    }

    // 获取 HmacSHA256
    public static byte[] getHmacSha256Key() {
        return getHmacKey("HmacSHA256");
    }

    // 获取 HmacSHA512
    public static byte[] getHmacSha512Key() {
        return getHmacKey("HmacSHA512");
    }

    // 获取 HMAC Key
    public static byte[] getHmacKey(String type) {
        try {
            // 1、创建密钥生成器
            KeyGenerator keyGenerator = KeyGenerator.getInstance(type);
            // 2、产生密钥
            SecretKey secretKey = keyGenerator.generateKey();
            // 3、获取密钥
            byte[] key = secretKey.getEncoded();
            return key;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // HMAC MD5 加密
    public static String encryptHmacMD5(byte[] data, byte[] key) {
        Mac mac = HmacUtils.getInitializedMac(HmacAlgorithms.HMAC_MD5, key);
        return Hex.encodeHexString(mac.doFinal(data));
    }

    // HMAC SHA256 加密
    public static String encryptHmacSHA256(byte[] data, byte[] key) {
        Mac mac = HmacUtils.getInitializedMac(HmacAlgorithms.HMAC_SHA_256, key);
        return Hex.encodeHexString(mac.doFinal(data));
    }

    // HMAC SHA521 加密
    public static String encryptHmacSHA512(byte[] data, byte[] key) {
        Mac mac = HmacUtils.getInitializedMac(HmacAlgorithms.HMAC_SHA_512, key);
        return Hex.encodeHexString(mac.doFinal(data));
    }

}

# 测试
import org.apache.commons.codec.binary.Hex;
import java.nio.charset.Charset;
import static com.ychen.demo01.util.CCHmacUtils.*;

public class Test1 {
    public static void main(String[] args) {
        byte[] data = "java小工匠".getBytes(Charset.forName("UTF-8"));
        // MD5
        byte[] hmacMd5KeyBytes = getHmacMd5Key();
        String hexHamcMd5Key = Hex.encodeHexString(hmacMd5KeyBytes);
        System.out.println("HMAC Md5 密钥:" + hexHamcMd5Key);
        String hmacMd5Encrypt = encryptHmacMD5(data, hmacMd5KeyBytes);
        System.out.println("HMAC Md5 加密:" + hmacMd5Encrypt);
        // SHA256
        byte[] hmacSha256KeyBytes = getHmacSha256Key();
        String hexHamcSha256Key = Hex.encodeHexString(hmacSha256KeyBytes);
        System.out.println("HMAC SHA256 密钥:" + hexHamcSha256Key);
        String hmacSha256Encrypt = encryptHmacSHA256(data, hmacSha256KeyBytes);
        System.out.println("HMAC SHA256 加密:" + hmacSha256Encrypt);
        // SHA512
        byte[] hmacSha512KeyBytes = getHmacSha512Key();
        String hexHamcSha512Key = Hex.encodeHexString(hmacSha512KeyBytes);
        System.out.println("HMAC SHA512 密钥:" + hexHamcSha512Key);
        String hmacSha512Encrypt = encryptHmacSHA512(data, hmacSha512KeyBytes);
        System.out.println("HMAC SHA512 加密:" + hmacSha512Encrypt);
    }
}

import java.nio.charset.Charset;
import static com.ychen.demo01.util.JdkHmacUtils.*;

public class Test2 {
    public static void main(String[] args) {
        byte[] data = "java小工匠".getBytes(Charset.forName("UTF-8"));
        // MD5
        byte[] hmacMd5KeyBytes = getHmacMd5Key();
        String hexHamcMd5Key = encodeHex(hmacMd5KeyBytes);
        System.out.println("HMAC Md5 密钥:" + hexHamcMd5Key);
        String hmacMd5Encrypt = encryptHmacMD5(data, hmacMd5KeyBytes);
        System.out.println("HMAC Md5 加密:" + hmacMd5Encrypt);
        // SHA256
        byte[] hmacSha256KeyBytes = getHmacSha256Key();
        String hexHamcSha256Key = encodeHex(hmacSha256KeyBytes);
        System.out.println("HMAC SHA256 密钥:" + hexHamcSha256Key);
        String hmacSha256Encrypt = encryptHmacSHA256(data, hmacSha256KeyBytes);
        System.out.println("HMAC SHA256 加密:" + hmacSha256Encrypt);
        // SHA512
        byte[] hmacSha512KeyBytes = getHmacSha512Key();
        String hexHamcSha512Key = encodeHex(hmacSha512KeyBytes);
        System.out.println("HMAC SHA512 密钥:" + hexHamcSha512Key);
        String hmacSha512Encrypt = encryptHmacSHA512(data, hmacSha512KeyBytes);
        System.out.println("HMAC SHA512 加密:" + hmacSha512Encrypt);
    }
}
# 控制台
HMAC Md5 密钥:104b0def3111b010d6da21c126d65419705881aab7757bcdfd4fc7c1a6a63b7bff122bd1c8c7c10cca8be5f87b5b1327a49a330e8e7cf2455d4ddf80f0bbd8f0
HMAC Md5 加密:57e09fba144d627529102285b5391283
HMAC SHA256 密钥:0bbc4cd63d28a11374c93b369092b5a8b3d57643eb47f800a83596369de1b5a1
HMAC SHA256 加密:4a8cdb2c14e0b15ebb3c934ca6f01b9295418d39d64515ad409c7bad92846bc9
HMAC SHA512 密钥:b82d412c34b53b1b231036ebce2fa93f6de4ea3d85008d4aebae47229d9be0fd60416fcb4e49022cae5ce530a4fa6c23ddee945cbda7e356bdaae8d2d90811e4
HMAC SHA512 加密:a17484359bbd8cbb41b3aa0c1fd06abf5c8ca109700a7333ec0fbca7cd4fa059e91be59d2557b45543541484c29dc451873dc41e843fecb9d2bbcdf9e48ff661

HMAC Md5 密钥:dcb6970b4b31543dfa353587ce5236c2487ee58e5170bf41feb28467cb751c0d9787a2006d6ea1b94a34beeba9b1939229dd683515b0fabe4fbda327afa4af93
HMAC Md5 加密:4689c834446baa41e91d6035f9a00b30
HMAC SHA256 密钥:d0a2c39157c0413fc5d6be3d1fb1b2ccbf331d8f2e735fc8b07d3a084726e880
HMAC SHA256 加密:452c4e6e45cab4376564ac7ee6e7c624d1cf619ef59b704df5876a305d361604
HMAC SHA512 密钥:af2c7d176270c7271d82a897315880a98e143e60e98e7e8d160669a19534a1351cdab194a8078cf991a1a49a5d2af734e216f1c41d3c0acbcf269850c67332d5
HMAC SHA512 加密:bb64012a34cf577ecf11dc5c145cfb429f58068244fca567243910454ab1f23eb395cc4de5a16b484a191faa0528677348d56b5008f0ab4e5858804563befe72
posted @ 2022-05-07 16:58  DogLeftover  阅读(304)  评论(0编辑  收藏  举报