Created
October 1, 2016 22:44
-
-
Save ihaveamac/7aa81f857947b86d57d39a0521cc5883 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import os | |
import sys | |
from Crypto.Cipher import AES | |
from Crypto.Hash import SHA256 | |
if len(sys.argv) < 4: | |
sys.exit("encrypt_keysector.py <otp> <secret_sector> <output>") | |
if os.path.getsize(sys.argv[1]) != 256: | |
sys.exit("OTP is invalid size (must br 256 bytes)") | |
if os.path.getsize(sys.argv[2]) != 512: | |
sys.exit("secret sector is invalid size (must br 512 bytes)") | |
def to_bytes(num): | |
numstr = b'' | |
tmp = num | |
while len(numstr) < 16: | |
numstr += bytes([tmp & 0xFF]) | |
tmp >>= 8 | |
return numstr[::-1] | |
# used from http://www.falatic.com/index.php/108/python-and-bitwise-rotation | |
rol = lambda val, r_bits, max_bits: \ | |
(val << r_bits%max_bits) & (2**max_bits-1) | \ | |
((val & (2**max_bits-1)) >> (max_bits-(r_bits%max_bits))) | |
with open(sys.argv[1], "rb") as f: | |
otp = f.read(0x90) | |
with open(sys.argv[2], "rb") as f: | |
sector = f.read(512) | |
otp_hash = SHA256.new(otp).hexdigest() | |
key_x = int(otp_hash[0:32], 16) | |
key_y = int(otp_hash[32:64], 16) | |
normal_key = rol((rol(key_x, 2, 128) ^ key_y) + 0x1FF9E9AAC5FE0408024591DC5D52768A, 87, 128) | |
cipher = AES.new(to_bytes(normal_key), AES.MODE_ECB) | |
with open(sys.argv[3], "wb") as f: | |
f.write(cipher.encrypt(sector)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment