将Hex转换为base64

The cryptopals crypto challenges

这是一个密码挑战
可以使用大多数主流语言,解决问题
环境:Python3.7.0
项目地址:http://cryptopals.com/sets/1/challenges/1

Convert hex to base64

将 hex(16进制)

1
49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d

打印为base64

1
SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t

base64和hex是一种编码手段,易还原
Base64本质上是一个ASCII字符表,其对应值64(0-63)个值
1.png
每个base64数字恰好代表6 bits。因此,三个8 bits(即24位)可以由四个6 bits的base64表示。
列如:设定ASCII字符串EVA,将对其进行base64编码

  • 1 - 将字符串–>十六进制
    ---ASCII/hex---
    E = 69d = 0x45
    V = 86d = 0x56
    A = 65d = 0x41
    
  • 2 - 十六进制–>二进制
    0x45 = 0100 0101
    0x56 = 0101 0110
    0x41 = 0100 0001
    
  • 3 - 将二进制字符串01000101 01010110 01000001总数除以6,得到4个对应base64字符的值
    010001 010101 011001 000001
    010001 = 17d = R
    010101 = 21d = V
    011001 = 25d = Z
    000001 = 1d = B
    

验证方案:

1
2
3
4
5
6
import base64

a = base64.b64encode('EVA'.encode('utf-8'))
print(str(a, 'utf-8'))

>>> RVZB

当不能被6整除时,在编码末尾加入一个或两个=(=代表000000)

代码实现1

1
2
3
4
5
6
7
import base64
import binascii

string = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d"
raw = binascii.unhexlify(string)
bin_raw = base64.b64encode(raw).decode()
print(bin_raw)

代码实现2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# -*- coding=UTF-8 -*-
b64_table = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"


def b64_encode(input_bytes):
# base64编码实现

# 初始化变量
encoding_output = ''
# 将输入字符转换为二进制,并创建1和0的列表
bit_list = list(''.join([bin(byte)[2:].zfill(8) for byte in input_bytes]))

# 将bit_list列表划分为6 bits一组
chunks = [bit_list[i:i + 6] for i in range(0, len(bit_list), 6)]

for chunk in chunks:
# 将chunks转化为010010这类
chunk = ''.join(chunk)

#检查chunk长度,根据需要在末尾添加'='字符
if len(chunk) == 2:
if '1' in chunk:
chunk += '0000'
encoding_output += b64_table[int(chunk, 2)] + '=='
else:
encoding_output += '=='
elif len(chunk) == 4:
if '1' in chunk:
chunk += '00'
encoding_output += b64_table[int(chunk, 2)] + '='
else:
encoding_output += '='
elif len(chunk) == 6:
encoding_output += b64_table[int(chunk, 2)]
return encoding_output


def main():
string = '49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d'
byte_string = bytes.fromhex(string)
print(b64_encode(byte_string))


if __name__ == '__main__':
main()

到此结束

如有错误请联系lanbaidetanlang@qq.com

文章目录
  1. 1. The cryptopals crypto challenges
    1. 1.1. Convert hex to base64
    2. 1.2. 代码实现1
    3. 1.3. 代码实现2
  2. 2. 到此结束