zoukankan      html  css  js  c++  java
  • 数字信息摘要常见算法

    编解码算法

    1. Hex 编码 
    将二进制数据按16进制转换为字符串,1字节=2个字符,编码后体积为2倍。

    2. Base64 
    由MIME规范定义的编码算法,其将3个字节(24位)编码为4个字符。 
    字符集包括64个,可表示6二进制位的数据,因此一个字符对应一组6bit的数据。 
    编码后体积约为4/3倍,针对不足位数用=补齐。

    HASH 算法

    通常也称散列算法,是一种将任意长度的消息变成固定长度的消息摘要算法,不可逆;

    1 MD5 
    Message Digest Algorithm 5,流行度极高,但目前被发现存在碰撞冲突风险; 
    任意长度输出为128bit=16字节摘要

    2 SHA1 
    SHA 指Security Hash Algorithm,由美国国家安全局NSA设计的安全散列算法系列; 
    SHA1 输出长度为160bit=20字节摘要

    3 SHA256 
    继SHA1 出现的算法(属于SHA-2类),安全性较SHA1更高; 
    SHA256 输出长度为256bit=32字节摘要。

    MAC 算法

    Message Authentication Code,消息认证码算法,基于HASH算法之上,增加了密钥的支持以提高安全性。 
    具体算法包括HmacMD5/HmacSHA1/HmacSHA256等,输入包括数据及密钥,输出长度与HASH算法一致。 
    密钥可以是任意长度的数据。

    代码样例

    HEX 编解码

        /**
         * Write a byte array as hexadecimal String.
         */
        public static String byteToHexString(byte[] bytes) {
            return String.valueOf(Hex.encodeHex(bytes));
        }
        /**
         * Transform an hexadecimal String to a byte array.
         */
        public static byte[] hexStringToByte(String hexString) {
            try {
                return Hex.decodeHex(hexString.toCharArray());
            } catch (DecoderException e) {
                throw new RuntimeException(e);
            }
        }  
    
    // Hex 来自 common-codec 扩展包
    // 字节编码片段
        private static final char[] DIGITS_LOWER =
            {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};  
        /**
         * @param data
         *            a byte[] to convert to Hex characters
    
         * @return A char[] containing hexadecimal characters
         * @since 1.4
         */
        protected static char[] encodeHex(final byte[] data) {
            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++] = DIGITS_LOWER [(0xF0 & data[i]) >>> 4];
                out[j++] = DIGITS_LOWER [0x0F & data[i]];
            }
            return out;
        }  

    Base64编解码

        /**
         * Encode a String to base64
         * 
         * @param value
         *            The plain String
         * @return The base64 encoded String
         */
        public static String encodeBASE64(String value) {
            try {
                return new String(Base64.encodeBase64(value.getBytes("utf-8")));
            } catch (UnsupportedEncodingException ex) {
                throw new RuntimeException(ex);
            }
        }
        /**
         * Decode a base64 value
         * 
         * @param value
         *            The base64 encoded String
         * @return decoded binary data
         */
        public static byte[] decodeBASE64(String value) {
            try {
                return Base64.decodeBase64(value.getBytes("utf-8"));
            } catch (UnsupportedEncodingException ex) {
                throw new RuntimeException(ex);
            }
        } 

    MD5 实现(SHA1、SHA256类似)

        /**
         * Build an hexadecimal MD5 hash for a String
         * 
         * @param value
         *            The String to hash
         * @return An hexadecimal Hash
         */
        public static String hexMD5(String value) {
            try {
                MessageDigest messageDigest = MessageDigest.getInstance("MD5");
                messageDigest.reset();
                messageDigest.update(value.getBytes("utf-8"));
                byte[] digest = messageDigest.digest();
                return byteToHexString(digest);
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        } 

    MAC 计算摘要

    static {
            // add bouncycastle support for md4 etc..
            Security.addProvider(new BouncyCastleProvider());
        }
        /**
         * 初始化密钥
         * 
         * @param type
         * @return
         */
        public static String initHmacKey(MacType type) {
            try {
                KeyGenerator generator = KeyGenerator.getInstance(type.name());
                SecretKey secretKey = generator.generateKey();
                byte[] key = secretKey.getEncoded();
                return Codec.byteToHexString(key);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        /**
         * 计算HMAC摘要
         * 
         * @param data
         * @param key
         * @param type
         * @return
         */
        public static String computeHmac(byte[] data, String key, MacType type) {
            try {
                byte[] keydata = Codec.hexStringToByte(key);
                SecretKey secretKey = new SecretKeySpec(keydata, type.name());
                Mac mac = Mac.getInstance(secretKey.getAlgorithm());
                mac.init(secretKey);
                byte[] digest = mac.doFinal(data);
                return Codec.byteToHexString(digest);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }  

    bouncycastle 支持

    maven 依赖

            <dependency>
                <groupId>org.bouncycastle</groupId>
                <artifactId>bcprov-jdk15on</artifactId>
                <version>1.54</version>
            </dependency> 

    http://www.bouncycastle.org/

  • 相关阅读:
    linux下base命令
    lldpd-0.7.7代码解读(send_pdu部分)
    openwrt 包makefile
    字符
    AC_CONFIG_HEADER
    大小端
    查看使用了那种shell
    debia下安装libjpeg
    工作流模式 (zhuan)
    1.2.1 工作流管理系统参考模型 (zhuan)
  • 原文地址:https://www.cnblogs.com/littleatp/p/6192864.html
Copyright © 2011-2022 走看看