MD5 method of Android encryption

foreword

Due to security considerations, the key value and other parameters in the sign need to be signed and encrypted by MD5, which can effectively protect the data of the application.

Introduction

MD5 is Message-Digest Algorithm 5 (Message-Digest Algorithm 5), which is used to ensure complete and consistent information transmission. It is one of the hash algorithms widely used by computers (also translated digest algorithm, hash algorithm), and MD5 is generally implemented in mainstream programming languages. The operation of data (such as Chinese characters) into another fixed-length value is the basic principle of the hash algorithm. The predecessors of MD5 are MD2, MD3 and MD4.
The MD5 algorithm has the following characteristics:
1. Compressibility: For data of any length, the length of the calculated MD5 value is fixed.
2. Easy to calculate: It is easy to calculate the MD5 value from the original data.
3. Modification resistance: any modification to the original data, even if only one byte is modified, the MD5 value obtained is very different.
4. Strong anti-collision: Knowing the original data and its MD5 value, it is very difficult to find a data with the same MD5 value (that is, fake data).
The purpose of MD5 is to allow large amounts of information to be "compressed" into a secure format (that is, to convert a string of bytes of arbitrary length into a string of hexadecimal digits of a certain length) before signing the private key with digital signature software.

Common uses of MD5

  • When the login password is protected, the password is encrypted by MD5 and then uploaded to the database, which can prevent the password from being hijacked and cracked. For example, if the password is 123456, if it is uploaded in plain text, the account can be easily stolen after being obtained. If it is encrypted with md5, it will become "49ba59abbe56e057", so even if it is hijacked, it is difficult to reverse translate this string of characters into 123456

  • Checking File
    Integrity When transferring files over the network, sometimes the file transfer is incomplete due to the influence of the network environment. The common method at this time is to use the md5 check code. If the md5 of the two files is the same, then the file is downloaded completely, if not, the download is not complete.

use

MD5 encryption is irreversible (it can be cracked now, please search the Internet for more information), and the encrypted string can be 16-bit or 32-bit. It must be noted that MD5 encryption is case-sensitive, otherwise the encrypted results will be different.

/**
 * Created by ${zk} on 2018/4/25 0025.
 * 欢迎每一天
 */

public class MD5sign {
    private static char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
            '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

    public static String getBytesMD5(byte[] bytes) {
        try {

            // 获得MD5摘要算法的 MessageDigest 对象
            MessageDigest mdInst = MessageDigest.getInstance("MD5");

            // 使用指定的字节更新摘要
            mdInst.update(bytes);

            // 获得密文
            byte[] md = mdInst.digest();

            // 把密文转换成十六进制的字符串形式
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 返回字符串的32位MD5值
     *
     * @param s
     *            字符串
     * @return str MD5值
     */
    public final static String getStringMD5(String s) {
        return getBytesMD5(s.getBytes());
    }

    /**
     * 返回字符串的16位MD5值
     *
     * @param s
     *            字符串
     * @return str MD5值
     */
    public final static String getStringMD5_16(String s) {
        return getStringMD5(s).substring(8, 24);
    }

    public final static String getBitmapMD5(Bitmap bm) {
        return getBytesMD5(bitmapToBytes(bm));
    }

    public final static String getBitmapMD5_16(Bitmap bm) {
        return getBytesMD5(bitmapToBytes(bm)).substring(8, 24);
    }

    public static byte[] bitmapToBytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }

    /**
     * 加密文件 
     * @param file  
     * @return 视频 音乐
     */
    public static String md5ForFile(File file){
        int buffersize = 1024;
        FileInputStream fis = null;
        DigestInputStream dis = null;

        try {
            //创建MD5转换器和文件流
            MessageDigest messageDigest =MessageDigest.getInstance("MD5");
            fis = new FileInputStream(file);
            dis = new DigestInputStream(fis,messageDigest);

            byte[] buffer = new byte[buffersize];
            //DigestInputStream实际上在流处理文件时就在内部就进行了一定的处理
            while (dis.read(buffer) > 0);

            //通过DigestInputStream对象得到一个最终的MessageDigest对象。
            messageDigest = dis.getMessageDigest();

            // 通过messageDigest拿到结果,也是字节数组,包含16个元素
            byte[] array = messageDigest.digest();
            // 同样,把字节数组转换成字符串
            StringBuilder hex = new StringBuilder(array.length * 2);
            for (byte b : array) {
                if ((b & 0xFF) < 0x10){
                    hex.append("0");
                }
                hex.append(Integer.toHexString(b & 0xFF));
            }
            return hex.toString();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324891318&siteId=291194637