关于md5和aes加密的的结果以及 16进制的转换

   一. 关于字符串与16进制的转换
String str = "Hello World";
StringBuilder hexStr = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
    hexStr.append(String.format("%02x", (int) str.charAt(i)));
}
System.out.println("16进制表示为:" + hexStr.toString());



运行结果:16进制表示为:48656c6c6f20576f726c64
  • String.format()方法用于格式化字符串,其中%02x表示以16进制形式输出,不足两位时前面补0。
  • (int) str.charAt(i)将字符转换为ASCII码值。
  • StringBuilder用于拼接字符串。
二.MD5加密后的长度都是定长的128位哈希值,即32位16进制数据。一共占用16字节。

三 AES加密

AES-128是一种区块加密算法,其处理的数据块大小固定为128位(16字节)。无论输入数据的实际长度是多少,加密后的数据都会以16字节的块来表示。如果原始数据不是16字节的倍数,那么需要进行填充(Padding)以满足这个要求。

aes加密的明文是30个字节 ,那他加密的逻辑是什么?

他会分成一个是16字节 一个是14字节的数据块,并对14字节的数据块进行补全16字节,然后再加密。加密后拼接起来。

明文如果是16字节, 那么加密后的密文也是16个字节。所以明文如果是16个字节的倍数的话,那密文和明文的长度相同。

四.aesdemo
    public static void main(String[] args) throws Exception {
//            生成32位的的16进制字符串
//        String content=RandomUtils.generateRandomHexString(32);
        String content="1f4976ee90992305a7e28ca645cbc915";
        System.out.println(content);
        byte[] KEY = MD5.MD5Encode2("CHZD12KTNX190930430");
        String encStr=aesEncryptBluetooth(content, KEY);
        System.out.println(encStr);
        System.out.println(ByteUtils.bytes2HexStr(aesDecryptByBytesBluetooth(encStr, KEY)));
        System.out.println(hexEncode(aesDecryptByBytesBluetooth(encStr, KEY)));


    }

    /**
     * 加密  将16进制的字符串加密
     */
    public static String aesEncryptBluetooth(String hexStr, byte[] cabinetMd5) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR2);
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(cabinetMd5, "AES"));
        return hexEncode(cipher.doFinal(ByteUtils.hexStr2Bytes(hexStr)));

    }

    /**
     * 解密 将16进制的字符串解密
     * @param hexStr
     * @param cabinetMd5
     * @return
     * @throws Exception
     */
    public static byte[] aesDecryptByBytesBluetooth(String hexStr, byte[] cabinetMd5) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);

        Cipher cipher = Cipher.getInstance(ALGORITHMSTR2);
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(cabinetMd5, "AES"));
        byte[] decryptBytes = cipher.doFinal(ByteUtils.hexStr2Bytes(hexStr));
        return decryptBytes;
    }

输出结果

1f4976ee90992305a7e28ca645cbc915
08919dcc0c03684fc894bea8679b0653
1f4976ee90992305a7e28ca645cbc915
1f4976ee90992305a7e28ca645cbc915

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值