# Matasano Crypto Challenge - Set 1 Challenge 1
def numericCh(ch):
'''
returns the numeric ascii representation of a given character
Assumes that all characteres are lower case
'''
if ch.isalpha():
return ord(ch) - ord('a') + 10
else:
return ord(ch) - ord('0')
def encodeHexStrToRawBytes(hexString):
'''
Converts HexString to hexadecimal raw bytes, saves on a list and returns it
Assumes that the len of hexString is a multiple of 2
'''
return [numericCh(hexString[i]) << 4 | numericCh(hexString[i+1]) for i in range(0, len(hexString), 2)]
hexString = '49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d'
rawBytes = encodeHexStrToRawBytes(hexString)
def decodeRawBytesToBase64(rawBytes):
'''
Decode a sequence of hexadecimal raw bytes to the base 64
'''
b64Map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
encodedString = []
pad = len(rawBytes) % 3
if pad == 1:
rawBytes.append(0)
rawBytes.append(0)
elif pad == 2:
rawBytes.append(0)
for i in range(0, len(rawBytes), 3):
encodedString.append(b64Map[rawBytes[i] >> 0b10])
encodedString.append(b64Map[((rawBytes[i] & 0b11) << 0b100) | (rawBytes[i+1] >> 0b100)])
encodedString.append(b64Map[((rawBytes[i+1] & 0b1111) << 0b10) | (rawBytes[i+2] >> 0b110)])
encodedString.append(b64Map[rawBytes[i+2] & 0b111111])
if pad > 0:
while pad != 0:
encodedString.append(b64Map[-1])
pad -= 1
return encodedString
hexString = '49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d'
rawBytes = encodeHexStrToRawBytes(hexString)
encodedString = decodeRawBytesToBase64(rawBytes)