def __init__(self, key): self.key = process_key(key) self.sm4_encryptor = CryptSM4() self.sm4_encryptor.set_key(self.key, SM4_ENCRYPT) self.sm4_decryptor = CryptSM4() self.sm4_decryptor.set_key(self.key, SM4_DECRYPT)
def decrypt_ecb(key, cipher): assert len(key) == 16 from gmssl.sm4 import CryptSM4, SM4_DECRYPT crypt_sm4 = CryptSM4(SM4_DECRYPT) crypt_sm4.set_key(key, SM4_DECRYPT) crypt_sm4.mode = 2 # todo: set `mode` neither `SM4_ENCRYPT` nor `SM4_DECRYPT` to avoid padding return crypt_sm4.crypt_ecb(cipher)
def SM4(): from gmssl.sm4 import CryptSM4, SM4_ENCRYPT, SM4_DECRYPT pri_key = binascii.unhexlify(params.get('pri_key')) dec_data = binascii.unhexlify(params.get('dec_data')) enc_data = binascii.unhexlify(params.get('enc_data')) iv = binascii.unhexlify(params.get('iv')) action = params.get('action') sm4_t = params.get('sm4_type') if sm4_t not in sm4_type: help_info_and_exit(-1) crypt_sm4 = CryptSM4() if sm4_t == "ecb": if action == 'encrypt': crypt_sm4.set_key(pri_key, SM4_ENCRYPT) encrypt_value = crypt_sm4.crypt_ecb(dec_data) output_hex(encrypt_value) elif action == 'decrypt': crypt_sm4.set_key(pri_key, SM4_DECRYPT) decrypt_value = crypt_sm4.crypt_ecb(enc_data) output_hex(decrypt_value) elif sm4_t == 'cbc': if action == 'encrypt': crypt_sm4.set_key(pri_key, SM4_ENCRYPT) encrypt_value = crypt_sm4.crypt_cbc(iv, dec_data) output_hex(encrypt_value) elif action == 'decrypt': crypt_sm4.set_key(pri_key, SM4_DECRYPT) dec_value = crypt_sm4.crypt_cbc(iv, enc_data) output_hex(dec_value)
def sm4_encrypt(m, k): crypt_sm4 = CryptSM4() crypt_sm4.set_key(k, 0) m = bytes_to_list(m) result = crypt_sm4.one_round(crypt_sm4.sk, m) result = list_to_bytes(result) return result
def decrypt_data_cbc(encrypted_text): encrypted_bytes = bytes.fromhex( base64.b64decode(encrypted_text).decode(encoding=ENCODING_UTF8)) crypt_sm4 = CryptSM4() crypt_sm4.set_key(KEY.encode(encoding=ENCODING_UTF8), SM4_DECRYPT) decrypt_bytes = crypt_sm4.crypt_ecb(encrypted_bytes) return decrypt_bytes.decode(ENCODING_UTF8)
def get_decrypt_str(x): # 解码 crypt_sm4 = CryptSM4() y = base64.b64decode(x.encode("utf8")) crypt_sm4.set_key(key, SM4_DECRYPT) decrypt_value = crypt_sm4.crypt_ecb(y) # bytes类型 return decrypt_value.decode()
def crypt_cfb(input_data, crypt_mode): crypt_sm4 = CryptSM4() crypt_sm4.mode = crypt_mode i = 0 output_data = [] tmp = [0] * 16 iv_tmp = bytes_to_list(iv) if crypt_sm4.mode == SM4_ENCRYPT: crypt_sm4.set_key(iv_tmp, SM4_ENCRYPT) input_data = padding(bytes_to_list(input_data)) length = len(input_data) while length > 0: tmp[0:16] = crypt_sm4.one_round(crypt_sm4.sk, iv_tmp[0:16]) output_data += xor(tmp[0:16], input_data[i:i + 16]) iv_tmp = copy.deepcopy(output_data[i:i + 16]) i += 16 length -= 16 return list_to_bytes(output_data) else: crypt_sm4.set_key(iv_tmp, SM4_ENCRYPT) length = len(input_data) while length > 0: tmp[0:16] = crypt_sm4.one_round(crypt_sm4.sk, iv_tmp[0:16]) output_data += xor(tmp[0:16], input_data[i:i + 16]) iv_tmp = copy.deepcopy(input_data[i:i + 16]) i += 16 length -= 16 return unpadding(list_to_bytes(output_data))
def get_decrypt_str(OOO0000O0O00O0OOO): #line:40 O0000OO0OO0O0000O = CryptSM4() #line:42 OOOO0O0O0O00O0OO0 = base64.b64decode( OOO0000O0O00O0OOO.encode("utf8")) #line:43 O0000OO0OO0O0000O.set_key(key, SM4_DECRYPT) #line:44 O00O00OO0O0O00OO0 = O0000OO0OO0O0000O.crypt_ecb( OOOO0O0O0O00O0OO0) #line:45 return O00O00OO0O0O00OO0.decode() #line:46
def sm4encrype(key, content): key = bytes(key, encoding='utf-8') content_bytes = content.encode() crypt_sm4 = CryptSM4() crypt_sm4.set_key(key, SM4_ENCRYPT) encrypt_value = crypt_sm4.crypt_ecb(content_bytes) # bytes类型 # print("加密结果:", encrypt_value) return encrypt_value
def _decrypt(key_str, data_bytes): # ->str if data_bytes == None: return None assert len(key_str) == 16 key_bytes = bytes(key_str, encoding='utf-8') crypt_sm4 = CryptSM4() crypt_sm4.set_key(key_bytes, SM4_DECRYPT) decrypted_data = crypt_sm4.crypt_ecb(data_bytes) # bytes类型 return str(decrypted_data, encoding='utf-8')
def _encrypt(key_str, data_str): # ->bytes if data_str == None: return None assert len(key_str) == 16 key_bytes = bytes(key_str, encoding='utf-8') data_bytes = bytes(data_str, encoding='utf-8') crypt_sm4 = CryptSM4() crypt_sm4.set_key(key_bytes, SM4_ENCRYPT) return crypt_sm4.crypt_ecb(data_bytes) # bytes类型
def set_crypt_str(input_str): # 加密 input_str = str.encode(input_str) crypt_sm4 = CryptSM4() crypt_sm4.set_key(key, SM4_ENCRYPT) encrypt_value = crypt_sm4.crypt_ecb(input_str) # bytes类型 crypt_str = base64.b64encode(encrypt_value).decode('utf8') return crypt_str
def set_crypt_str(OO000O0000OOO0O00): #line:29 OO000O0000OOO0O00 = str.encode(OO000O0000OOO0O00) #line:31 OOO0OO00OO0OOO0OO = CryptSM4() #line:32 OOO0OO00OO0OOO0OO.set_key(key, SM4_ENCRYPT) #line:33 OO0000OO0O00O00O0 = OOO0OO00OO0OOO0OO.crypt_ecb( OO000O0000OOO0O00) #line:34 OOOO00OOO00000O0O = base64.b64encode(OO0000OO0O00O00O0).decode( 'utf8') #line:36 return OOOO00OOO00000O0O #line:37
def sm4_cbc(value): crypt_sm4 = CryptSM4() crypt_sm4.set_key(key, SM4_ENCRYPT) encrypt_value = crypt_sm4.crypt_cbc(iv, value) crypt_sm4.set_key(key, SM4_DECRYPT) decrypt_value = crypt_sm4.crypt_cbc(iv, encrypt_value) save_file("logo.png", ".\\result\\logo_cbc_en.png", encrypt_value) save_file("logo.png", ".\\result\\logo_cbc_de.png", decrypt_value) if value == decrypt_value: print("CBC is ok!")
def sm4_enc(value_s, key_s): crypt_sm4 = CryptSM4() iv = b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' value = bytes(value_s, 'utf-8') key = bytes(key_s, 'utf-8') crypt_sm4.set_key(key, SM4_ENCRYPT) encrypt_value = crypt_sm4.crypt_cbc(iv, value) encrypt_value = func.bytes_to_list(encrypt_value) encrypt_value = [hex(i) for i in encrypt_value] return encrypt_value
def sm4_ecb(value): crypt_sm4 = CryptSM4() crypt_sm4.set_key(key, SM4_ENCRYPT) encrypt_value = crypt_sm4.crypt_ecb(value) crypt_sm4.set_key(key, SM4_DECRYPT) decrypt_value = crypt_sm4.crypt_ecb(encrypt_value) save_file("logo.png", ".\\result\\logo_ecb_en.png", encrypt_value) save_file("logo.png", ".\\result\\logo_ecb_de.png", decrypt_value) if value == decrypt_value: print("ECB is ok!")
def sm4cbc(outfile): crypt_sm4 = CryptSM4() crypt_sm4.set_key(key, SM4_ENCRYPT) with open("./pku_logo.rgb", 'rb') as f: logo_data = f.read() encrypt_logo = crypt_sm4.crypt_cbc(iv, logo_data) f.close() with open(outfile, 'wb') as f: f.write(encrypt_logo) f.close()
def sm4_ecb_mode(str1): crypt_sm4 = CryptSM4() crypt_sm4.set_key(key, SM4_ENCRYPT) with open("./pku_logo.rgb", 'rb') as f: logo_data = f.read() # print(type(logo_data)) encrypt_logo = crypt_sm4.crypt_ecb(logo_data) f.close() with open(str1, 'wb') as f: f.write(encrypt_logo) f.close()
def test_sm4_cbc(basic_loop, rand_bytes): for _ in range(basic_loop): crypt_sm4 = CryptSM4() msg = rand_bytes(random.randint(1, 100)) key = rand_bytes(16) iv = rand_bytes(16) crypt_sm4.set_key(key, SM4_ENCRYPT) enc = crypt_sm4.crypt_cbc(iv, msg) crypt_sm4.set_key(key, SM4_DECRYPT) dec = crypt_sm4.crypt_cbc(iv, enc) assert dec == msg
def decryptData_ECB(self, cipher_text): crypt_sm4 = CryptSM4() secret_key = b"JeF38U9wT9wlMfs2" print(secret_key) crypt_sm4.set_key(secret_key, SM4_DECRYPT) # 将转入参数base64.b64decode解码成十六进制的bytes类型 byt_cipher_text = base64.b64decode(cipher_text) # 调用加密方法解密,解密后为bytes类型 decrypt_value = crypt_sm4.crypt_ecb(byt_cipher_text) print(decrypt_value) print(decrypt_value.decode('utf-8', 'ignore')) print(json.dumps(decrypt_value.decode('utf-8', 'ignore'))) return decrypt_value.decode('utf-8', 'ignore')
def sm4_encrypt(key, content): ''' sm4加密 :param key: 密钥 :param content: 要加密的字符串 :return: 加密后的字节数据 ''' key = bytes(key, encoding='utf-8') content_bytes = content.encode() crypt_sm4 = CryptSM4() crypt_sm4.set_key(key, SM4_ENCRYPT) encrypt_value = crypt_sm4.crypt_ecb(content_bytes) # bytes类型 # print("加密结果:", encrypt_value) return encrypt_value
def crypt_ctr(input_data, mode): crypt_sm4 = CryptSM4() i = 0 output_data = [] tmp = [0] * 16 ctr_tmp = ctr ctr_tmp_list = bytes_to_list(("%016x" % ctr_tmp).encode('ascii')) crypt_sm4.set_key(ctr_tmp_list, SM4_ENCRYPT) if mode == SM4_ENCRYPT: input_data = padding(bytes_to_list(input_data)) length = len(input_data) while length > 0: tmp[0:16] = crypt_sm4.one_round(crypt_sm4.sk, ctr_tmp_list[0:16]) output_data += xor(tmp[0:16], input_data[i:i + 16]) ctr_tmp += 1 ctr_tmp_list = bytes_to_list(("%016x" % ctr_tmp).encode('ascii')) i += 16 length -= 16 if mode == SM4_DECRYPT: return unpadding(list_to_bytes(output_data)) return list_to_bytes(output_data)
def save_to_file(self, filename, password=None): content = {} key = self.keypair.private_key content["address"] = self.keypair.address content["encrypt"] = False if password is not None: crypt_sm4 = CryptSM4() password = self.pwd_ljust(password) crypt_sm4.set_key(bytes(password, "utf-8"), SM4_ENCRYPT) encrypt_value = crypt_sm4.crypt_cbc( self.cbc_iv, bytes(self.keypair.private_key, "utf-8")) key = str(base64.b64encode(encrypt_value), "utf-8") content["encrypt"] = True content["private_key"] = key content["type"] = "gm" # set mac of the password passwdBytes = bytes(password, "utf-8") content["mac"] = sm3.sm3_hash(passwdBytes) with open(filename, "w") as dump_f: json.dump(content, dump_f, indent=4) dump_f.close()
def encryptData_ECB(self, plain_text): # 创建 SM4对象 crypt_sm4 = CryptSM4() # 定义key值 secret_key = b"JeF38U9wT9wlMfs2" # print("key: ", secret_key) # 设置key crypt_sm4.set_key(secret_key, SM4_ENCRYPT) # 调用加密方法加密(十六进制的bytes类型) encrypt_value = crypt_sm4.crypt_ecb(plain_text) # print("encrypt_value: ", encrypt_value) # 用base64.b64encode转码(编码后的bytes) cipher_text = base64.b64encode(encrypt_value) # print("加密后:", cipher_text) # print(cipher_text.decode('utf-8', 'ignore')) # 返回加密后的字符串 return cipher_text.decode('utf-8', 'ignore')
def load_from_file(self, filename, password=None): if password is None: return with open(filename, "r") as dump_f: content = json.load(dump_f) dump_f.close() if content["type"] != "gm": return # get and compare mac expected_mac = content["mac"] password = self.pwd_ljust(password) passwdBytes = bytes(password, "utf-8") mac = sm3.sm3_hash(passwdBytes) if not hmac.compare_digest(mac, expected_mac): raise ValueError("MAC mismatch") key = content["private_key"] crypt_sm4 = CryptSM4() crypt_sm4.set_key(bytes(password, "utf-8"), SM4_DECRYPT) key = base64.b64decode(bytes(key, "utf-8")) key = str(crypt_sm4.crypt_cbc(self.cbc_iv, key), "utf-8") self.from_key(key)
def decrypt(info_raw, file_enc): endianness = func.endianness data = func.destructure(file_enc)[0] # decrypt sm4 key private_key = info_raw['decrypt key'] public_key = '' sm2_crypt = sm2.CryptSM2(public_key=public_key, private_key=private_key) sm4_key = sm2_crypt.decrypt(data['sm4_key']) # verify digestn lf = len(file_enc) # if sm3.hash(file_enc[lf - 142:lf - 32]) != file_enc[lf - 32:]: # return 'block digest unmatch' visited = data['flags'][0] >= 8 * 16 prev_info = func.parse_info(file_enc[lf - 110:lf - 32]) if visited: prev_signature = prev_info['signature'] prev_id = prev_info['id'] prev_pubkey = None # verify the previous visitor's signature # this shall be done by the server # but here we use local csv file for demonstration # with open('database/keypairs.csv') as file: # kps = csv.reader(file) # for kp in kps: # if kp[0] == prev_id: # prev_pubkey = kp[2] # break # assert prev_pubkey != None, 'signer not found' # sm2_verify = sm2.CryptSM2(public_key=prev_pubkey, private_key='') # prev_sign_data = file_enc[lf - 110:lf - 106] + file_enc[lf - 42:lf - 32] # assert sm2_verify.verify(prev_signature, prev_sign_data) ip_addr = socket.gethostbyname(socket.gethostname()) my_info = { 'time_stamp': int(time.time()).to_bytes(4, endianness), 'signature': b'', 'ip_addr': b''.join([int(i).to_bytes(1, endianness) for i in ip_addr.split('.')]), 'id': info_raw['id'].encode('ascii') } sm2_sign = sm2.CryptSM2(public_key='', private_key=info_raw['private key']) random_hex_str = func.random_hex(sm2_crypt.para_len) sign_data = my_info['time_stamp'] + my_info['ip_addr'] + my_info['id'] my_info['signature'] = bytes.fromhex( sm2_sign.sign(sign_data, random_hex_str)) # decypt file crypt_sm4 = CryptSM4() crypt_sm4.set_key(sm4_key, SM4_DECRYPT) file_data = crypt_sm4.crypt_ecb(data['file_encrypted']) # update the visitor's chain # post the my_info dict to the server # with open('database/visitors.csv', 'w', newline='') as file: # writer = csv.writer(file) # writer.writerow([repr(my_info[key]) for key in my_info]) try: viewer.viewPdfBytes(file_data) except RuntimeError: return 'wrong decrypt key' return [repr(my_info[key]) for key in my_info] # class QtGui(QWidget): # def __init__(self): # super().__init__() # self.initUI() # def initUI(self): # self.structureLabel = QLabel('Enc-File Decrypter') # self.structureLabel.setStyleSheet(''' # color: #333; # font-size: 35px; # font-weight: 700; # margin-top: 10px; # margin-bottom: 35px; # ''') # self.idLabel = QLabel('user ID ') # # self.pubkeyLabel = QLabel('public key ') # self.pvtkeyLabel = QLabel('private key') # self.deckeyLabel = QLabel('decrypt key') # for item in [self.idLabel, self.pvtkeyLabel, self.deckeyLabel]: # item.setStyleSheet(''' # width: 200px; # color: #333; # font-size: 25px; # font-weight: 400; # ''') # self.idEdit = QLineEdit() # # self.pubkeyEdit = QLineEdit() # self.pvtkeyEdit = QLineEdit() # self.deckeyEdit = QLineEdit() # for item in [self.idEdit, self.pvtkeyEdit, self.deckeyEdit]: # item.setStyleSheet(''' # padding: 5px 8px; # width: 600px; # font-size: 22px; # color: #333; # margin-left: 10px; # ''') # self.fileBtn = QPushButton('Select File', self) # self.fileBtn.clicked.connect(self.openFile) # self.fileBtn.setStyleSheet(''' # background-color: #80aaff; # color: white; # margin: 25px; # width: 140px; # height: 30px; # padding: 10px 24px; # border: none; # font-weight: 1000; # font-size: 22px; # ''') # self.msgLabel = QLabel('') # self.msgLabel.setStyleSheet(''' # color: #ff6666; # font-size: 26px; # font-weight: 500; # ''') # labelHbox = QHBoxLayout() # labelHbox.addStretch(1) # labelHbox.addWidget(self.structureLabel) # labelHbox.addStretch(1) # idHbox = QHBoxLayout() # idHbox.addStretch(1) # idHbox.addWidget(self.idLabel) # idHbox.addWidget(self.idEdit) # idHbox.addStretch(1) # # pubkeyHbox = QHBoxLayout() # # pubkeyHbox.addStretch(1) # # pubkeyHbox.addWidget(self.pubkeyLabel) # # pubkeyHbox.addWidget(self.pubkeyEdit) # # pubkeyHbox.addStretch(1) # pvtkeyHbox = QHBoxLayout() # pvtkeyHbox.addStretch(1) # pvtkeyHbox.addWidget(self.pvtkeyLabel) # pvtkeyHbox.addWidget(self.pvtkeyEdit) # pvtkeyHbox.addStretch(1) # deckeyHbox = QHBoxLayout() # deckeyHbox.addStretch(1) # deckeyHbox.addWidget(self.deckeyLabel) # deckeyHbox.addWidget(self.deckeyEdit) # deckeyHbox.addStretch(1) # btnHbox = QHBoxLayout() # btnHbox.addStretch(1) # btnHbox.addWidget(self.fileBtn) # btnHbox.addStretch(1) # msgHbox = QHBoxLayout() # msgHbox.addStretch(1) # msgHbox.addWidget(self.msgLabel) # msgHbox.addStretch(1) # vbox = QVBoxLayout() # vbox.addStretch(1) # vbox.addLayout(labelHbox) # vbox.addLayout(idHbox) # # vbox.addLayout(pubkeyHbox) # vbox.addLayout(pvtkeyHbox) # vbox.addLayout(deckeyHbox) # vbox.addLayout(btnHbox) # vbox.addLayout(msgHbox) # vbox.addStretch(1) # self.setLayout(vbox) # self.step = 0 # self.setGeometry(500, 250, 900, 500) # self.setWindowTitle('D3CRYPT decrypter') # self.setWindowIcon(QIcon('img/key.png')) # self.setStyleSheet("background-color: white;") # self.show() # def showMsg(self, content): # self.msgLabel.setText(content) # def openFile(self): # info_raw = { # 'id': self.idEdit.text(), # # 'public key': self.pubkeyEdit.text(), # 'private key': self.pvtkeyEdit.text(), # 'decrypt key': self.deckeyEdit.text() # } # for key in info_raw: # if len(info_raw[key]) == 0: # self.showMsg(key + ' cannot be empty') # return # try: # int(info_raw[key], 16) # except ValueError: # self.showMsg(key + ' is invalid') # return # self.showMsg('') # fname = QFileDialog.getOpenFileName(self, 'Open file', r'D:\\projects\\cryptocontest\\project') # if fname[0]: # if '.enc' not in fname[0]: # self.showMsg('invalid document\nyou should select a .enc file') # return # self.showMsg('') # self.showMsg(main(info_raw, fname[0])) # if __name__ == '__main__': # app = QApplication(sys.argv) # gui = QtGui() # sys.exit(app.exec_())
file = open(name, 'wb') file.write(img) file.close() def picture_to_bytes(): # 图片转换为字节 with open(r'logo/PKU.jpg', 'rb') as f: res = base64.b64encode(f.read()) return res res = picture_to_bytes() # 将图片转换为字节 key = b'3l5butlj26hvv313' value = res # bytes类型 iv = b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' # bytes类型 crypt_sm4 = CryptSM4() # ECB模式对logo进行加密 crypt_sm4.set_key(key, SM4_ENCRYPT) encrypt_value = crypt_sm4.crypt_ecb(value) # bytes类型 bytes_to_picture(encrypt_value, 'EBC_encrypt.jpg') # ECB对logo进行解密 crypt_sm4.set_key(key, SM4_DECRYPT) decrypt_value = crypt_sm4.crypt_ecb(encrypt_value) # bytes类型 bytes_to_picture(decrypt_value, 'EBC_decrypt.jpg') # CBC模式对logo进行加密 crypt_sm4.set_key(key, SM4_ENCRYPT) encrypt_value = crypt_sm4.crypt_cbc(iv, value) # bytes类型
def do_validate(): msg = open("input.txt", 'rb').read() crypt_sm4 = CryptSM4() crypt_sm4.set_key(key, SM4_ENCRYPT) cipher = crypt_sm4.crypt_cbc(iv, msg) # bytes类型 return cipher
def encrypt_data_cbc(original_text): crypt_sm4 = CryptSM4() crypt_sm4.set_key(KEY.encode(encoding=ENCODING_UTF8), SM4_ENCRYPT) encrypt_data = crypt_sm4.crypt_ecb( original_text.encode(encoding=ENCODING_UTF8)) return base64.b64encode(encrypt_data).decode(encoding=ENCODING_UTF8)
def __init__(self): self.crypt_sm4 = CryptSM4()