MD5 哈希和 Base64 编码 [英] MD5 Hash and Base64 encoding

查看:13
本文介绍了MD5 哈希和 Base64 编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个 32 个字符的字符串(一个 MD5 哈希)并且我使用 Base64 对其进行编码,那么编码字符串的最大长度是多少?

If I have a 32 character string (an MD5 hash) and I encode it using Base64, what's the maximun length of the encoded string?

推荐答案

在 Base64 表示法中,MD5 值始终为 22(有用)字符.许多 Base64 算法在编码 MD5 散列时还会附加 2 个填充字符,使总数达到 24 个字符.填充没有添加有用的信息,可以丢弃.只有前 22 个字符很重要.

An MD5 value is always 22 (useful) characters long in Base64 notation. Many Base64 algorithms will also append 2 characters of padding when encoding an MD5 hash, bringing the total to 24 characters. The padding adds no useful information and can be discarded. Only the first 22 characters matter.

原因如下:

MD5 哈希是一个 128 位的值.Base64 字符串中的每个字符包含 6 位信息,因为该字符有 64 个可能的值,需要 2 的 6 次方才能达到 64.每个字符包含 6 位信息,21 个字符有 126 位信息,22 个字符包含 132 位信息.由于 128 位不能容纳在 21 个字符内,但可以容纳在 22 个字符内(留有一点余地),因此 128 位值在 Base64 中将始终表示为 22 个字符.

An MD5 hash is a 128-bit value. Every character in a Base64 string contains 6 bits of information, because there are 64 possible values for the character, and it takes 6 powers of 2 to reach 64. With 6 bits of information in every character, 21 characters has 126 bits of information, and 22 characters contains 132 bits of information. Since 128 bits cannot fit within 21 characters but does fit within 22 characters (with a little room to spare), a 128-bit value will always be represented as 22 characters in Base64.

关于填充的注释:

我在上面提到过许多 Base64 编码算法在对 MD5 值进行编码时会添加几个填充字符.这是因为 Base64 将 3 个字节的信息表示为 4 个字符.由于 MD5 有 16 个字节的信息,许多 Base64 编码算法会附加=="来指定 16 个字节的输入比下一个 3 的倍数少 2 个字节,即 18 个字节.这两个等号不向字符串添加任何信息,并且可以在存储时丢弃.

I mentioned above that many Base64 encoding algorithms add a couple of characters of padding when encoding an MD5 value. This is because Base64 represents 3 bytes of information as 4 characters. Since MD5 has 16 bytes of information, many Base64 encoding algorithms append "==" to designate that the input of 16 bytes was 2 bytes short of the next multiple of 3, which would have been 18 bytes. These 2 equal signs add no information whatsoever to the string, and can be discarded when storing.

这篇关于MD5 哈希和 Base64 编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆