android加密算法之MD5

Kornan
2020-08-14 / 0 评论 / 144 阅读 / 正在检测是否收录...

方法1

fun getMD5A(str: String): String? {
        return try {
            val md: MessageDigest = MessageDigest.getInstance("MD5")//生成一个MD5加密计算摘要
            md.update(str.toByteArray()) //计算md5函数
            var md5Str: String = BigInteger(1, md.digest()).toString(16)
            if (md5Str.length < 32) {
                md5Str = "0$md5Str"
            }
            md5Str
        } catch (e: Exception) {
            throw Exception("MD5加密出现错误")
        }
    }

方法2,修改hexDigits可生所不同的字符串:例如:charArrayOf('5','2','0','1','3','1','4','7','8','9','a','b','c','d','e','f')

fun getMD5B(str: String): String? {
        val hexDigits = charArrayOf('0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f')
        return try {
            val mdInst = MessageDigest.getInstance("MD5")
            mdInst.update(str.toByteArray())
            val md = mdInst.digest()
            val j = md.size
            val str = CharArray(j * 2)
            var k = 0
            for (i in 0 until j) {
                val byte0 = md[i]
                str[k++] = hexDigits[byte0.toInt().ushr(4) and 0xf]
                str[k++] = hexDigits[byte0.toInt().and(0xf)]
            }
            String(str)
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
            null
        }
    }
0

评论

博主关闭了当前页面的评论