def runRC4(msg, key): rc4 = RC4(key) ciphertext = rc4.encrypt(msg) rc4 = RC4(key) decrypted = rc4.decrypt(ciphertext) assert msg == decrypted
def __init__(self): self.publicKey = rsa.PublicKey.load_pkcs1_openssl_pem(b"-----BEGIN PUBLIC KEY-----\nMFswDQYJKoZIhvcNAQEBBQADSgAwRwJAeyjMOLhcK4o2AnFRhn8vPteUy5Fux/cXN/J+wT/zYIEUINo02frn+Kyxx0RIXJ3CvaHkwmueVL8ytfqo8Ol/OwIDAQAB\n-----END PUBLIC KEY-----") self.remoteHostAddr = "51.222.11.213" self.remoteHostPort = 2050 # use this key to decrypt packets from the server self.clientReceiveKey = RC4(bytearray.fromhex("612a806cac78114ba5013cb531")) # use this key to send packets to the server self.serverRecieveKey = RC4(bytearray.fromhex("BA15DE")) self.headers = { 'User-Agent': "Mozilla/5.0 (Windows; U; en-US) AppleWebKit/533.19.4 (KHTML, like Gecko) AdobeAIR/32.0", 'Referer' : 'app:/Valor.swf', 'x-flash-version' : '32,0,0,170' } self.email = None self.password = None self.buildVersion = "3.2.2" self.serverSocket = None # state consistency self.charID = None self.objectID = None self.charID = None self.reconnecting = False self.connected = False # this is in milliseconds self.clientStartTime = int(time.time() * 1000) self.ignoreIn = [] """
def __init__(self, key): RC4.__init__(self, key, "cryptlib") self.context = cryptlib_py.cryptCreateContext( cryptlib_py.CRYPT_UNUSED, cryptlib_py.CRYPT_ALGO_RC4) cryptlib_py.cryptSetAttribute(self.context, cryptlib_py.CRYPT_CTXINFO_KEYSIZE, len(key)) cryptlib_py.cryptSetAttributeString(self.context, cryptlib_py.CRYPT_CTXINFO_KEY, key)
def test_rc4text(self): p = "boomstick" r = 5 t = "Hello World" encoding = "Latin1" rc4 = RC4(p.encode(encoding), r) e = rc4.CryptText(t) rc4 = RC4(p.encode(encoding), r) d = rc4.CryptText(e.decode(encoding)).decode(encoding) assert d == t
def __init__(self, key): RC4.__init__(self, key, "python") keyBytes = stringToBytes(key) S = [i for i in range(256)] j = 0 for i in range(256): j = (j + S[i] + keyBytes[i % len(keyBytes)]) % 256 S[i], S[j] = S[j], S[i] self.S = S self.i = 0 self.j = 0
def test_rc4file(self): p = "boomstick" r = 5 encoding = "Latin1" rc4 = RC4(p.encode(encoding), r) rc4.CryptFile("testfiles\\file.dat", "testfiles\\file.dat.enc") assert not cmp("testfiles\\file.dat", "testfiles\\file.dat.enc", False) rc4 = RC4(p.encode(encoding), r) rc4.CryptFile("testfiles\\file.dat.enc", "testfiles\\file.dat.dec") assert cmp("testfiles\\file.dat", "testfiles\\file.dat.dec", False) os.remove("testfiles\\file.dat.enc") os.remove("testfiles\\file.dat.dec")
def run(self): global Globalvariable count = 0 while 1: if not Globalvariable["RSA_Sent"]: self.connexion.send( str("##Rsapubkeyis#" + str(Globalvariable['e']) + "#" + str(Globalvariable['n'])).encode("Utf8")) time.sleep(1) elif Globalvariable["RSA_Sent"] and Globalvariable[ "RSA_Recieved"] and not Globalvariable["RC4_sent"]: self.connexion.send( str("##RC4#" + str(Globalvariable['EncRC4Key'])).encode("Utf8")) time.sleep(1) elif Globalvariable["RC4_sent"]: if count == 0: print("##### You are connected") count = count + 1 message_emis = input() Rc4 = RC4() Rc4.shuffle(Globalvariable["RC4Key"]) m = Rc4.Crypt(message_emis) self.connexion.send(m.encode("Utf8"))
def run(self): global Globalvariable while 1: message_recu = self.connexion.recv(1024).decode("Utf8") if message_recu[0:14] == "##Rsapubkeyis#": if not Globalvariable['RSA_Recieved']: message = message_recu[14:].split("#") Globalvariable['OtherRsaE'], Globalvariable[ 'OtherRsaN'] = int(message[0]), int(message[1]) self.connexion.send("##YesRsa".encode("Utf8")) Rsa = RSA() Globalvariable["EncRC4Key"] = Rsa.crypt( Globalvariable["OtherRsaE"], Globalvariable["OtherRsaN"], Globalvariable["RC4Key"]) Globalvariable['RSA_Recieved'] = True color_print( "Public Anahtarı -->" + str(Globalvariable["OtherRsaE"]) + str(Globalvariable["OtherRsaN"]), 'red') color_print( "RC4 Private Anahtarı -->" + Globalvariable["RC4Key"], 'red') color_print( "Şifrelenmiş Anahtar -->" + str(Globalvariable["EncRC4Key"]), 'red') else: self.connexion.send("##YesRsa".encode("Utf8")) elif message_recu == "##YesRsa": Globalvariable['RSA_Sent'] = True elif message_recu[:6] == "##RC4#": if Globalvariable["OtherRC4"] == "": Rsa = RSA() Globalvariable["OtherRC4"] = Rsa.decrypt( Globalvariable["d"], Globalvariable["n"], int(message_recu[6:])) self.connexion.send("##YesRC4".encode("Utf8")) else: self.connexion.send("##YesRC4".encode("Utf8")) elif message_recu == "##YesRC4": if not Globalvariable["RC4_sent"]: Globalvariable["RC4_sent"] = True elif Globalvariable['RSA_Sent'] and Globalvariable[ 'RSA_Recieved'] and message_recu[ 0: 14] != "##Rsapubkeyis#" and message_recu != "##YesRsa" and message_recu != "##YesRC4": Rc44 = RC4() Rc44.shuffle(str(Globalvariable["OtherRC4"])) message = Rc44.Crypt(message_recu) color_print("Mesaj -->" + message, 'yellow') color_print("Şifrelenmiş Mesaj -->" + message_recu, 'blue')
def DecryptFile(self, infile, outfile, key, rounds=20, encoding="iso-8859-1"): if not path.isfile(infile): raise Exception("Input file does not exist.") with open(infile, 'rb') as src: with open(outfile, 'wb') as dest: keybytes = key[:246].encode(encoding) + src.read(10) rc4 = RC4(keybytes, rounds) while True: data = bytearray(src.read(1048576)) if len(data) == 0: break dest.write(rc4.CryptBytes(data))
def fun_load_db(): global myDB mutex_db.acquire() try: with open(db_file, 'rb') as infile: # 从文件加载数据 enc_json = infile.read() # 解密 dump_rc4 = RC4() dump_rc4.set_key(base_rc4_key.encode()) str_json = dump_rc4.do_enc(enc_json).decode('utf-8') # load myDB = json.loads(str_json) print('load DB from file success') except FileNotFoundError: print('load DB from file failed') mutex_db.release()
def run(self): global Globalvariable while 1: message_recu = self.connexion.recv(1024).decode("Utf8") if message_recu[0:14] == "##Rsapubkeyis#": if not Globalvariable['RSA_Recieved']: message = message_recu[14:].split("#") Globalvariable['OtherRsaE'], Globalvariable[ 'OtherRsaN'] = int(message[0]), int(message[1]) self.connexion.send("##YesRsa".encode("Utf8")) Rsa = RSA() Globalvariable["EncRC4Key"] = Rsa.crypt( Globalvariable["OtherRsaE"], Globalvariable["OtherRsaN"], Globalvariable["RC4Key"]) Globalvariable['RSA_Recieved'] = True else: self.connexion.send("##YesRsa".encode("Utf8")) elif message_recu == "##YesRsa": Globalvariable['RSA_Sent'] = True elif message_recu[:6] == "##RC4#": if Globalvariable["OtherRC4"] == "": Rsa = RSA() Globalvariable["OtherRC4"] = Rsa.decrypt( Globalvariable["d"], Globalvariable["n"], int(message_recu[6:])) self.connexion.send("##YesRC4".encode("Utf8")) else: self.connexion.send("##YesRC4".encode("Utf8")) elif message_recu == "##YesRC4": if not Globalvariable["RC4_sent"]: Globalvariable["RC4_sent"] = True elif Globalvariable['RSA_Sent'] and Globalvariable[ 'RSA_Recieved'] and message_recu[ 0: 14] != "##Rsapubkeyis#" and message_recu != "##YesRsa" and message_recu != "##YesRC4": Rc44 = RC4() Rc44.shuffle(str(Globalvariable["OtherRC4"])) message = Rc44.Crypt(message_recu) print("---->>> " + message)
def startRC4(self, plaintext, outputfilename): #possibly input a filestream #print("PLAINTEXT OF STREAM: {0}".format(plaintext)) if self.communicate_flag: rc_cipher = RC4(self.symmetricKey) x = 0 #chunk number out_file = open(outputfilename, "wb") hasher = SHA384.new() while (x + 1) * BLOCK_SIZE < len(plaintext): ciphertext = rc_cipher.run(plaintext[x * BLOCK_SIZE:(x + 1) * BLOCK_SIZE]) ciphertext = array.array( 'B', ciphertext).tobytes() #last 6 bytes will be new key hasher.update(ciphertext) self.symmetricKey = ciphertext[len(ciphertext) - SYMMETRIC_KEY_SIZE:] #print("Bob {0}: {1}".format(x,self.symmetricKey)) x = x + 1 #print("CIPHERTEXT OF STREAM: {0}".format(ciphertext)) out_file.write(ciphertext) rc_cipher.changeKey(self.symmetricKey) #hash ciphertext? #change key? ciphertext = rc_cipher.run( plaintext[x * BLOCK_SIZE:len(plaintext) - SHA384_SIZE]) #is -1 correct? ciphertext = array.array('B', ciphertext).tobytes() hasher.update(ciphertext) endhash = plaintext[len(plaintext) - SHA384_SIZE:] #print("THIS HASHES DIGEST {0}".format(hasher.digest())) #print("DIGEST OF ALICE'S HASH {0}".format(endhash)) #print("RC4 CIPHERTEXT: {0}".format(ciphertext)) out_file.write(ciphertext) out_file.close() self.validateDigest(endhash, hasher.digest()) else: print("Unable to communicate")
def startRC4(self, plaintext, outputfilename): #possibly input a filestream if self.communicate_flag: rc_cipher = RC4(self.symmetricKey) x = 0 #chunk number out_file = open(outputfilename, "wb") hasher = SHA384.new() while (x + 1) * (BLOCK_SIZE - SYMMETRIC_KEY_SIZE) < len(plaintext): self.symmetricKey = get_random_bytes( SYMMETRIC_KEY_SIZE ) # New key to be used, should this be done? message = plaintext[x * (BLOCK_SIZE - SYMMETRIC_KEY_SIZE):(x + 1) * (BLOCK_SIZE - SYMMETRIC_KEY_SIZE)] + self.symmetricKey hasher.update(message) ciphertext = rc_cipher.run(message) ciphertext = array.array('B', ciphertext).tobytes() #print("Alice {0}: {1}".format(x,self.symmetricKey)) x = x + 1 out_file.write(ciphertext) rc_cipher.changeKey(self.symmetricKey) #self.symmetricKey = get_random_bytes(SYMMETRIC_KEY_SIZE) #!! Don't need to have a new key at the end of the message message = plaintext[x * (BLOCK_SIZE - SYMMETRIC_KEY_SIZE):] hasher.update(message) ciphertext = rc_cipher.run(message) ciphertext = array.array('B', ciphertext).tobytes() out_file.write(ciphertext) out_file.write(hasher.digest()) out_file.close() else: print("Unable to communicate")
def fun_timer_dump(): global timer_dump, cur_dump_version mutex_db.acquire() # 比较dump版本和DB版本,决定是否需要dump数据到文件 if cur_dump_version < cur_db_version: # dump json_str = json.dumps(myDB, ensure_ascii=False) # 加密 dump_rc4 = RC4() dump_rc4.set_key(base_rc4_key.encode()) enc_json = dump_rc4.do_enc(json_str.encode('utf-8')) # 写入文件 with open(db_file, 'wb') as outfile: outfile.write(enc_json) # 更新dump版本 cur_dump_version = cur_db_version print('fun_timer_dump dump done. cur_db_version: %d' % cur_db_version) mutex_db.release() # 循环定时器 timer_dump = threading.Timer(timer_dump_interval, fun_timer_dump) timer_dump.start()
def __init__(self, key): RC4.__init__(self, key, "openssl") self.rc4 = m2.rc4_new() m2.rc4_set_key(self.rc4, key)
def call_RC4(): key = input("Enter a secret key: ") text = input("Text to encrypt or hex to decrypt: ") text = RC4(key, text) print(text)
def test_benchbytes(self, benchmark): encoding = "Latin1" size = 10 * 1024 * 1024 b = bytearray(size) rc4 = RC4("boomstick".encode(encoding), 5) benchmark(self.bench_rc4bytes, rc4, b)
def test_RC4TestEnc1(self): algorithm = RC4() cipher = algorithm.Encrypt("abcd", "test") self.assertEqual(cipher, "ÏíDu")
import sys from RC4 import RC4 from package_io import fun_receive_pack, fun_unpack_receive_data, fun_pack_send_data, fun_send_pack user = '******' pin = 'DSinmSGza79KV/AGrSDYP+j8Frjw1e9WTAPYrmN8tDM=' sheet = 'default' # 通讯根密钥 base_rc4_key = 'CloudBlackboard_rc4_base_key' server_ip_port = ('127.0.0.1', 1986) # server_ip_port = ('beautyli.cn', 16821) rc4 = RC4() def do_request(__request): request_data = json.dumps(__request).encode('utf-8') # 加密数据 send_data = fun_pack_send_data(rc4, request_data) # 发送数据 fun_send_pack(sock, send_data) # 接收数据 r_data = fun_receive_pack(sock) if not r_data: return None # 解密数据 data_unpack = fun_unpack_receive_data(rc4, r_data)
def test_RC4TestEnc(self): algorithm = RC4() cipher = algorithm.Encrypt("aaaa", "test") self.assertEqual(cipher, "ÏîFp")
def test_RC4TestDec(self): algorithm = RC4() cipher = algorithm.Decrypt("ÏîFp", "test") self.assertEqual(cipher, "aaaa")
def test_RC4TestDec1(self): algorithm = RC4() cipher = algorithm.Decrypt("ÏíDu", "test") self.assertEqual(cipher, "abcd")
def test_RC4TestDec2(self): algorithm = RC4() cipher = algorithm.Encrypt("0xcfed4475", "0x74657374") self.assertTrue(cipher, "0x61626364")
def fun_logon(rand, request): global myDB, register_user_count respond = {'result': 'failed', 'reason': 'bad request'} rc4 = None try: if request['transaction'] == 'logon': user = request['user'] challenge = base64.b64decode(request['challenge']) pin = myDB[user]['pin'] # 解密数据 rc4 = RC4() rc4.set_key((base_rc4_key + pin).encode()) enc_random = rc4.do_enc(rand) # 检验随机数 if enc_random == challenge: respond = {'result': 'success', 'user': user} else: respond = {'result': 'failed', 'reason': 'bad challenge'} elif request['transaction'] == 'register': challenge = base64.b64decode(request['challenge']) # 解密数据 rc4 = RC4() rc4.set_key(base_rc4_key.encode()) enc_random = rc4.do_enc(rand) pin = (rc4.do_enc(base64.b64decode(request['pin']))).decode() # 检验随机数 if enc_random != challenge: respond = {'result': 'failed', 'reason': 'bad challenge'} else: user = request['user'] if len(user) < 3: respond = { 'result': 'failed', 'reason': 'user name too short' } else: if user in myDB: respond = { 'result': 'failed', 'reason': 'user already registered' } else: if len(pin) < 6: respond = { 'result': 'failed', 'reason': 'pin too short' } else: if register_user_count >= register_user_count_limit: respond = { 'result': 'failed', 'reason': 'reach the register_user_count limit in 24 hour' } else: myDB[user] = { 'create_time': time.time(), 'pin': pin, 'box': { 'default': { 'ver': 0, 'note': {}, 'deleted': {} } } } respond = {'result': 'success', 'user': user} register_user_count += 1 except KeyError as e: respond = {'result': 'failed', 'reason': 'KeyError with ' + str(e)} except binascii.Error: pass return respond, rc4
def setCryptKey(self, stream_key, hmac_key): self.CIPHER_SEND = RC4() self.CIPHER_RECV = RC4() self.CIPHER_SEND.SetKey(stream_key) self.CIPHER_RECV.SetKey(stream_key) self.HMAC_KEY = hmac_key
def EncryptText(self, text, key, rounds=20, encoding="iso-8859-1"): iv = urandom(10) keybytes = key[:246].encode(encoding) + iv rc4 = RC4(keybytes, rounds) return iv + rc4.CryptText(text, encoding)
def __init__(self, key): RC4.__init__(self, key, "cryptlib") self.context = cryptlib_py.cryptCreateContext(cryptlib_py.CRYPT_UNUSED, cryptlib_py.CRYPT_ALGO_RC4) cryptlib_py.cryptSetAttribute(self.context, cryptlib_py.CRYPT_CTXINFO_KEYSIZE, len(key)) cryptlib_py.cryptSetAttributeString(self.context, cryptlib_py.CRYPT_CTXINFO_KEY, key)
def DecryptText(self, data, key, rounds=20, encoding="iso-8859-1"): keybytes = key[:246].encode(encoding) + data[:10] rc4 = RC4(keybytes, rounds) return rc4.CryptBytes(bytearray(data[10:])).decode(encoding)
#! python3 from CipherSaber import CipherSaber from RC4 import RC4 import os import time # rc4 = RC4("boomstick") # enc = rc4.CryptText("Hello World") # rc4 = RC4("boomstick") # dec = rc4.CryptText(enc) # print("Encoded: {}\nDecoded: {}".format(enc, dec)) size = 100 * 1024 * 1024 rc4 = RC4("boomstick".encode("iso-8859-1"), 5) b = bytearray(size) start = time.perf_counter() #print([i for i in rc4.CryptText("Hello World")]) #rc4.CryptBytes(b) rc4.CryptFile("testfiles/file.dat.enc", "testfiles/file.dat.dec") print("{} MB stream: {:4f}".format(size / 1024 / 1024, time.perf_counter() - start)) print("Last byte: {:#x}".format(b[-1])) ''' enc = CipherSaber().EncryptText("Hello World", "boomstick", 5) print(type(enc)) print([i for i in enc]) dec = CipherSaber().DecryptText(enc, "boomstick", 5) print(type(dec)) print(dec) '''