diff --git a/3DES/huanlv_code_3DES.py b/3DES/huanlv_code_3DES.py new file mode 100644 index 0000000..7e38143 --- /dev/null +++ b/3DES/huanlv_code_3DES.py @@ -0,0 +1,345 @@ +""" + Hướng dẫn cài đặt thuật toán: + + Sử dụng ngôn ngữ python để chạy mã code (version 3.7) + + Sau khi tải về mở powershell/termiral tại thư mục chứ file mã code + + Chạy lệnh " python huanlv_code_3DES.py " để quan sát +""" + +# Một số bảng cần dùng cho thuật toán 3DES +# Bảng hoán vị pc-1 +pc1 = ( + 57, 49, 41, 33, 25, 17, 9, + 1, 58, 50, 42, 34, 26, 18, + 10, 2, 59, 51, 43, 35, 27, + 19, 11, 3, 60, 52, 44, 36, + 63, 55, 47, 39, 31, 23, 15, + 7, 62, 54, 46, 38, 30, 22, + 14, 6, 61, 53, 45, 37, 29, + 21, 13, 5, 28, 20, 12, 4 + ) +# Bảng hoán vị pc-2 +pc2 = ( + 14, 17, 11, 24, 1, 5, 3, + 28, 15, 6, 21, 10, 23, 19, + 12, 4, 26, 8, 16, 7, 27, + 20, 13, 2, 41, 52, 31, 37, + 47, 55, 30, 40, 51, 45, 33, + 48, 44, 49, 39, 56, 34, 53, + 46, 42, 50, 36, 29, 32 + ) +# Bảng hoán vị đầu +ip = ( + 58, 50, 42, 34, 26, 18, 10, 2, + 60, 52, 44, 36, 28, 20, 12, 4, + 62, 54, 46, 38, 30, 22, 14, 6, + 64, 56, 48, 40, 32, 24, 16, 8, + 57, 49, 41, 33, 25, 17, 9, 1, + 59, 51, 43, 35, 27, 19, 11, 3, + 61, 53, 45, 37, 29, 21, 13, 5, + 63, 55, 47, 39, 31, 23, 15, 7 + ) +# Bảng hoán vị sau cùng +ip1 = ( + 40, 8, 48, 16, 56, 24, 64, 32, + 39, 7, 47, 15, 55, 23, 63, 31, + 38, 6, 46, 14, 54, 22, 62, 30, + 37, 5, 45, 13, 53, 21, 61, 29, + 36, 4, 44, 12, 52, 20, 60, 28, + 35, 3, 43, 11, 51, 19, 59, 27, + 34, 2, 42, 10, 50, 18, 58, 26, + 33, 1, 41, 9, 49, 17, 57, 25 + ) +# Bảng hoán vị mở rộng +e = ( + 32, 1, 2, 3, 4, 5, + 4, 5, 6, 7, 8, 9, + 8, 9, 10, 11, 12, 13, + 12, 13, 14, 15, 16, 17, + 16, 17, 18, 19, 20, 21, + 20, 21, 22, 23, 24, 25, + 24, 25, 26, 27, 28, 29, + 28, 29, 30, 31, 32, 1 + ) +# Các bảng s-Box +box = [ +# Box-1 +[ +[14,4,13,1,2,15,11,8,3,10,6,12,5,9,0,7], +[0,15,7,4,14,2,13,1,10,6,12,11,9,5,3,8], +[4,1,14,8,13,6,2,11,15,12,9,7,3,10,5,0], +[15,12,8,2,4,9,1,7,5,11,3,14,10,0,6,13] +], +# Box-2 + +[ +[15,1,8,14,6,11,3,4,9,7,2,13,12,0,5,10], +[3,13,4,7,15,2,8,14,12,0,1,10,6,9,11,5], +[0,14,7,11,10,4,13,1,5,8,12,6,9,3,2,15], +[13,8,10,1,3,15,4,2,11,6,7,12,0,5,14,9] +], + +# Box-3 + +[ +[10,0,9,14,6,3,15,5,1,13,12,7,11,4,2,8], +[13,7,0,9,3,4,6,10,2,8,5,14,12,11,15,1], +[13,6,4,9,8,15,3,0,11,1,2,12,5,10,14,7], +[1,10,13,0,6,9,8,7,4,15,14,3,11,5,2,12] + +], + +# Box-4 +[ +[7,13,14,3,0,6,9,10,1,2,8,5,11,12,4,15], +[13,8,11,5,6,15,0,3,4,7,2,12,1,10,14,9], +[10,6,9,0,12,11,7,13,15,1,3,14,5,2,8,4], +[3,15,0,6,10,1,13,8,9,4,5,11,12,7,2,14] +], + +# Box-5 +[ +[2,12,4,1,7,10,11,6,8,5,3,15,13,0,14,9], +[14,11,2,12,4,7,13,1,5,0,15,10,3,9,8,6], +[4,2,1,11,10,13,7,8,15,9,12,5,6,3,0,14], +[11,8,12,7,1,14,2,13,6,15,0,9,10,4,5,3] +], +# Box-6 + +[ +[12,1,10,15,9,2,6,8,0,13,3,4,14,7,5,11], +[10,15,4,2,7,12,9,5,6,1,13,14,0,11,3,8], +[9,14,15,5,2,8,12,3,7,0,4,10,1,13,11,6], +[4,3,2,12,9,5,15,10,11,14,1,7,6,0,8,13] + +], +# Box-7 +[ +[4,11,2,14,15,0,8,13,3,12,9,7,5,10,6,1], +[13,0,11,7,4,9,1,10,14,3,5,12,2,15,8,6], +[1,4,11,13,12,3,7,14,10,15,6,8,0,5,9,2], +[6,11,13,8,1,4,10,7,9,5,0,15,14,2,3,12] +], +# Box-8 + +[ +[13,2,8,4,6,15,11,1,10,9,3,14,5,0,12,7], +[1,15,13,8,10,3,7,4,12,5,6,11,0,14,9,2], +[7,11,4,1,9,12,14,2,0,6,10,13,15,3,5,8], +[2,1,14,7,4,10,8,13,15,12,9,0,3,5,6,11] +] + +] +# Bảng hoán vị P +p = ( + 16, 7, 20, 21, 29, 12, 28, 17, + 1, 15, 23, 26, 5, 18, 31, 10, + 2, 8, 24, 14, 32, 27, 3, 9, + 19, 13, 30, 6, 22, 11, 4, 25 + ) +# Bảng dịch chuyển bit +rk = (1,1,2,2,2,2,2,2,1,2,2,2,2,2,2,1) + +# Hàm tạo ra key 56 bits từ key 64 bits và bảng hoán vị pc1 +def applyPc1(key64bits): + key56bits = "" + for i in pc1: + key56bits += key64bits[i-1] + return key56bits +# Hàm cắt key 56 bits thành 2 key 28 bits +def cutHaftKey56bits(key56bits): + leftKey = key56bits[:28] + rightKey = key56bits[28:] + return leftKey,rightKey +# Hàm dịch bit +def leftShift(bits,numBits): + result = bits[numBits:]+bits[:numBits] + return result +# Hàm tạo key 48 bits từ key 56 bits và bảng pc2 +def applyPc2(key56bits): + key48bits = "" + for i in pc2: + key48bits += key56bits[i-1] + return key48bits +# Hàm tạo key (sẽ tạo ra 16 key) +def generateKeys(key64bits): + roundKeys = [] + pc1Out = applyPc1(key64bits) + L0,R0 = cutHaftKey56bits(pc1Out) + for i in range(16): + newL = leftShift(L0,rk[i]) + newR = leftShift(R0,rk[i]) + roundKey = applyPc2(newL+newR) + roundKeys.append(roundKey) + return roundKeys +def XOR(bits1,bits2): + xorResult = "" + for i in range(len(bits1)): + if bits1[i] == bits2[i]: + xorResult += '0' + else: + xorResult += '1' + return xorResult +# hàm nâng độ dài key từ 32 bit len 48 bit +def applyExpansion(bits32): + bits48 = "" + for i in e: + bits48 += bits32[i-1] + return bits48 +# Hàm cắt key 48 bít thành các dãy 6 bits +import textwrap +def cutTo6bits(str48bits): + result = textwrap.wrap(str48bits,6) + return result +# Một số hàm hỗ trợ +def getFirstLastBit(bits6): + return bits6[0]+bits6[-1] +def getMiddleBit(bits6): + return bits6[1:5] +def boxLookup(boxCount,firstLast,middle): + dFirstLast = binToDec(firstLast) + dMiddle = binToDec(middle) + + value = box[boxCount][dFirstLast][dMiddle] + return decToBin(value) +# Sử dụng bảng hoán vị p để hoán vị khối 32 bits(Khối L và R) +def applyP(s32bits): + result = "" + for i in p: + result += s32bits[i-1] + return result +# HÀM F +def functionF(pre32bits,key48bits): + result = "" + expanded_left_half = applyExpansion(pre32bits) + xor_value = XOR(expanded_left_half,key48bits) + bits6list = cutTo6bits(xor_value) + for sboxcount, bits6 in enumerate(bits6list): + first_last = getFirstLastBit(bits6) + middle4 = getMiddleBit(bits6) + sboxvalue = boxLookup(sboxcount,first_last,middle4) + result += sboxvalue + final32bits = applyP(result) + return final32bits +#Một số hàm chuyển đổi giữa các kiểu dữ liệu +def binToDec(bina): + decimal = int(bina,2) + return decimal +def decToBin(deci): + bin4bits = bin(deci)[2:].zfill(4) + return bin4bits +def textToHex(text): + return (text.encode("UTF-8")).hex() +def hexToText(hexText): + return (bytes.fromhex(hexText)).decode("UTF-8") +def hexToBin(hexdigits): + bindigits = "" + for hexdigit in hexdigits: + bindigits += bin(int(hexdigit,16))[2:].zfill(4) + return bindigits +def binToHex(text): + lookup = {"0000" : "0", "0001" : "1", "0010" : "2", "0011" : "3", "0100" : "4", "0101" : "5", "0110" : "6", "0111" : "7", "1000" : "8", "1001" : "9", "1010" : "a", "1011" : "b", "1100" : "c", "1101":"d" , "1110":"e" , "1111":"f"} + result = "" + for i in range(0,len(text),4): + result += lookup[text[i]+text[i+1]+text[i+2]+text[i+3]] + return result +#Sử dụng bảng hoán vị Ip +def applyIp(plaintext): + permutated = "" + for i in ip: + permutated += plaintext[int(i)-1] + return permutated +def spliHalf(binarybits): + return binarybits[:32],binarybits[32:] +def applyIp1(text): + cipher = "" + for index in ip1: + cipher += text[int(index)-1] + return cipher +"""MÃ HÓA VÀ GIẢI MÃ THEO THUẬT TOÁN DES""" +def encryptDes(message,key): + key = textToHex(key) + result="" + list64bits = textwrap.wrap(message,16) + for item in list64bits: + cipher = "" + # Chuyển key và message cần mã háo sang dạng nhị phân + plaintext_bits = hexToBin(item) + key_bits = hexToBin(key) + # Tạo key cho 16 vòng lặp + roundkeys = generateKeys(key_bits) + + # Áp dụng bảng hoán vị Ip + p_plaintext = applyIp(plaintext_bits) + ## Chia p_plaintext thành 2 nửa trái và phải + L,R = spliHalf(p_plaintext) + ## Mã hóa + for round in range(16): + newR = XOR(L,functionF(R, roundkeys[round])) + newL = R + R = newR + L = newL + cipher = applyIp1(R+L) + cipher = binToHex(cipher) + result += cipher + return result +def decryptDes(message,key): + result="" + list64bits = textwrap.wrap(message,16) + key = textToHex(key) + for item in list64bits: + text = "" + # Chuyển key và message cần mã háo sang dạng nhị phân + plaintext_bits = hexToBin(item) + key_bits = hexToBin(key) + # Tạo key cho 16 vòng lặp + roundkeys = generateKeys(key_bits) + + # Áp dụng bảng hoán vị Ip + p_plaintext = applyIp(plaintext_bits) + ## Chia p_plaintext thành 2 nửa trái và phải + L,R = spliHalf(p_plaintext) + ## Giải mã + for round in range(16): + newR = XOR(L,functionF(R, roundkeys[15-round])) + newL = R + R = newR + L = newL + text = applyIp1(R+L) + text = binToHex(text) + #result += hexToText(text) + result += text + return result +"""MÃ HÓA VÀ GIẢI MÃ THEO THUẬT TOÁN 3DES""" +def encrypt3Des(message,key): + message = textToHex(message) + listKey = textwrap.wrap(key,8) + temp1 = encryptDes(message,listKey[0]) + temp2 = decryptDes(temp1,listKey[1]) + temp3 = encryptDes(temp2,listKey[2]) + return temp3 +def decrypt3Des(message,key): + listKey = textwrap.wrap(key,8) + temp1 = decryptDes(message,listKey[2]) + temp2 = encryptDes(temp1,listKey[1]) + temp3 = decryptDes(temp2,listKey[0]) + return hexToText(temp3) + +"""TEST""" +check = True +while check: + print("""Enter your chose:\n\t1. Encode\n\t2. Decode\n\t3. Exit""") + chose = input("Your chose is: ") + if chose == '1': + key = input("[+]Enter your key: ") + text = input("[+]The text you want encode: ") + ciphertext = encrypt3Des(text,key) + print("*The text after encode: ",ciphertext+"\n"+"*"*35) + elif chose == '2': + key = input("[+]Enter your key: ") + text = input("[+]The text you want decode: ") + plaintext = decrypt3Des(text,key) + print("*The text after decode: ",plaintext+"\n"+"*"*35) + elif chose == '3': + check = False + else: + print("ERROR! You must chose 1,2 or 3.\n"+"*"*35) \ No newline at end of file diff --git a/3DES/report 3DES cipher.txt b/3DES/report 3DES cipher.txt new file mode 100644 index 0000000..fb8eca0 --- /dev/null +++ b/3DES/report 3DES cipher.txt @@ -0,0 +1,23 @@ +# Mã hóa Triple DES +* Người thực hiện: Lại Văn Huân + +#Lý thuyết +**Triple DES là gì? + -Triple DES là một biến thể của DES, được ra đời sau khi mã hóa DES không còn an toàn từ năm 1990 + -Hoạt động của Triple DES thực chất vẫn dựa trên thuật toán DES, thay vì chỉ mã hóa một lần thì Triple DES đã thực +hiện 3 lần gồm mã hóa và giải mã của thuật toán DES +**Triple DES hoạt động dựa vào 3 bước: + -Sinh khóa + -Mã hóa + -Giải mã +[+]Sinh khóa: + -Khóa chính đưa vào sẽ có độ dài 64*3 bits => chia thành 3 khóa con là key1, key2, key3 + -Các nhóm khóa con 48 bits được sinh ra từ key1, key2, key3 dựa trên thuật toán sinh khóa của DES +[+]Mã hóa: + -Quá trình mã hóa là tập hợp 3 bước liên tục của thuật toán DES: + +Mã hóa với key1 + +Giải mã với key2 + +Mã hóa với key3 +[+]Giải mã: + -Đảo ngược quá trình mã hóa ta sẽ được chuỗi sau giải mã. + diff --git a/3DES/run.png b/3DES/run.png new file mode 100644 index 0000000..b521fe5 Binary files /dev/null and b/3DES/run.png differ diff --git a/Caesar/Run.png b/Caesar/Run.png new file mode 100644 index 0000000..209e57a Binary files /dev/null and b/Caesar/Run.png differ diff --git a/Caesar/huanlv_code_Caesar.py b/Caesar/huanlv_code_Caesar.py new file mode 100644 index 0000000..322a421 --- /dev/null +++ b/Caesar/huanlv_code_Caesar.py @@ -0,0 +1,43 @@ +"""Encrypt the plaintext and return the ciphertext""" +def encrypt(key,change,plaintext): + result = "" + for c in plaintext: + try: + position = (key.index(c)+change) % len(key) + result += key[position] + except Exception: + result += c + return result + +"""Decrypt the plaintext and return the plaintext""" +def decrypt(key,change,ciphertext): + result = "" + for c in ciphertext: + try: + position = (key.index(c)-change) % len(key) + result += key[position] + except Exception: + result += c + return result + +"""The example of caesar algorithm""" +check = True +while check: + print("""Enter your chose:\n\t1. Encode\n\t2. Decode\n\t3. Exit""") + chose = input("Your chose is: ") + if chose == '1': + key = input("[+]Enter a custom alphabet: ") + text = input("[+]The text you want encode: ") + change = int(input("[+]Enter the shift< a number >:")) + ciphertext = encrypt(key,change,text) + print("*The text after encode: ",ciphertext+"\n"+"*"*35) + elif chose == '2': + key = input("[+]Enter a custom alphabet: ") + text = input("[+]The text you want decode: ") + change = int(input("[+]Enter the shift< a number >:")) + plaintext = decrypt(key,change,text) + print("*The text after decode: ",plaintext+"\n"+"*"*35) + elif chose == '3': + check = False + else: + print("ERROR! You must chose 1,2 or 3.\n"+"*"*35) \ No newline at end of file diff --git a/DES/huongnm_code_des.py b/DES/huongnm_code_des.py new file mode 100644 index 0000000..d344369 --- /dev/null +++ b/DES/huongnm_code_des.py @@ -0,0 +1,125 @@ +from sys import exit +from time import time + +KeyLength = 10 +SubKeyLength = 8 +DataLength = 8 +FLength = 4 + +# Bảng cho hoán vị ban đầu và cuối cùng (b1, b2, b3, ... b8) +IPtable = (2, 6, 3, 1, 4, 8, 5, 7) +FPtable = (4, 1, 3, 5, 7, 2, 8, 6) + +# Bảng để tạo khóa con (k1, k2, k3, ... k10) +P10table = (3, 5, 2, 7, 4, 10, 1, 9, 8, 6) +P8table = (6, 3, 7, 4, 8, 5, 10, 9) + +# Tables for the fk function +EPtable = (4, 1, 2, 3, 2, 3, 4, 1) +S0table = (1, 0, 3, 2, 3, 2, 1, 0, 0, 2, 1, 3, 3, 1, 3, 2) +S1table = (0, 1, 2, 3, 2, 0, 1, 3, 3, 0, 1, 0, 2, 1, 0, 3) +P4table = (2, 4, 3, 1) + +def perm(inputByte, permTable): + """Permute input byte according to permutation table""" + outputByte = 0 + for index, elem in enumerate(permTable): + if index >= elem: + outputByte |= (inputByte & (128 >> (elem - 1))) >> (index - (elem - 1)) + else: + outputByte |= (inputByte & (128 >> (elem - 1))) << ((elem - 1) - index) + return outputByte + +def ip(inputByte): + """Perform the initial permutation on data""" + return perm(inputByte, IPtable) + +def fp(inputByte): + """Perform the final permutation on data""" + return perm(inputByte, FPtable) + +def swapNibbles(inputByte): + """Swap the two nibbles of data""" + return (inputByte << 4 | inputByte >> 4) & 0xff + +def keyGen(key): + """Generate the two required subkeys""" + def leftShift(keyBitList): + """Perform a circular left shift on the first and second five bits""" + shiftedKey = [None] * KeyLength + shiftedKey[0:9] = keyBitList[1:10] + shiftedKey[4] = keyBitList[0] + shiftedKey[9] = keyBitList[5] + return shiftedKey + + # Converts input key (integer) into a list of binary digits + keyList = [(key & 1 << i) >> i for i in reversed(range(KeyLength))] + permKeyList = [None] * KeyLength + for index, elem in enumerate(P10table): + permKeyList[index] = keyList[elem - 1] + shiftedOnceKey = leftShift(permKeyList) + shiftedTwiceKey = leftShift(leftShift(shiftedOnceKey)) + subKey1 = subKey2 = 0 + for index, elem in enumerate(P8table): + subKey1 += (128 >> index) * shiftedOnceKey[elem - 1] + subKey2 += (128 >> index) * shiftedTwiceKey[elem - 1] + return (subKey1, subKey2) + +def fk(subKey, inputData): + """Apply Feistel function on data with given subkey""" + def F(sKey, rightNibble): + aux = sKey ^ perm(swapNibbles(rightNibble), EPtable) + index1 = ((aux & 0x80) >> 4) + ((aux & 0x40) >> 5) + \ + ((aux & 0x20) >> 5) + ((aux & 0x10) >> 2) + index2 = ((aux & 0x08) >> 0) + ((aux & 0x04) >> 1) + \ + ((aux & 0x02) >> 1) + ((aux & 0x01) << 2) + sboxOutputs = swapNibbles((S0table[index1] << 2) + S1table[index2]) + return perm(sboxOutputs, P4table) + + leftNibble, rightNibble = inputData & 0xf0, inputData & 0x0f + return (leftNibble ^ F(subKey, rightNibble)) | rightNibble + +def encrypt(key, plaintext): + """Encrypt plaintext with given key""" + data = fk(keyGen(key)[0], ip(plaintext)) + return fp(fk(keyGen(key)[1], swapNibbles(data))) + +def decrypt(key, ciphertext): + """Decrypt ciphertext with given key""" + data = fk(keyGen(key)[1], ip(ciphertext)) + return fp(fk(keyGen(key)[0], swapNibbles(data))) + +if __name__ == '__main__': + + + try: + assert encrypt(0b0000000000, 0b10101010) == 0b00010001 + except AssertionError: + print("Error on encrypt:") + print("Output: ", encrypt(0b0000000000, 0b10101010), "Expected: ", 0b00010001) + exit(1) + try: + assert encrypt(0b1110001110, 0b10101010) == 0b11001010 + except AssertionError: + print("Error on encrypt:") + print("Output: ", encrypt(0b1110001110, 0b10101010), "Expected: ", 0b11001010) + exit(1) + try: + assert encrypt(0b1110001110, 0b01010101) == 0b01110000 + except AssertionError: + print("Error on encrypt:") + print("Output: ", encrypt(0b1110001110, 0b01010101), "Expected: ", 0b01110000) + exit(1) + try: + assert encrypt(0b1111111111, 0b10101010) == 0b00000100 + except AssertionError: + print("Error on encrypt:") + print("Output: ", encrypt(0b1111111111, 0b10101010), "Expected: ", 0b00000100) + exit(1) + + t1 = time() + for i in range(1000): + encrypt(0b1110001110, 0b10101010) + t2 = time() + print("Elapsed time for 1,000 encryptions: {:0.3f}s".format(t2 - t1)) + exit() \ No newline at end of file diff --git a/RSA/cuonghq_code_rsa.py b/RSA/cuonghq_code_rsa.py new file mode 100644 index 0000000..e8656a7 --- /dev/null +++ b/RSA/cuonghq_code_rsa.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python3 +# +# virtualenv -p python3.7 name_env +# pip install -r requirement.txt +import random + +def is_prime(number): + return all([number % i for i in range(2, int(n**0.5) + 1)]) and number > 1 + +# Greatest common divisor +def GCD(p, q): + while q != 0: + p, q = q, p % q + return p + + +# Use Euclidean extended algorithm to compiting d +def egcd(p, q): + if p == 0: + return (q, 0, 1) + else: + g, x, y = egcd(q % p, p) + return (g, y - (q // p) * x, x) + +# Multiplicative inverse +def mulinv(e, fi): + g, x, y = egcd(e, fi) + return x % fi + + +def generate_keypair(p, q): + n = p * q + fi = (p - 1) * (q - 1) + e = random.randrange(1, fi) + gcd = GCD(e, fi) + while gcd != 1: + e = random.randrange(1, fi) + gcd = GCD(e, fi) + print(e) + d = mulinv(e, fi) + return ((e, n), (d, n)) + + +def encrypt(pk, ciphertext): + key, n = pk + cipher = [(ord(char) ^ key) % n for char in ciphertext] + return cipher + + +if __name__ == '__main__': + p = 5 + q = 7 + public, private = generate_keypair(p, q) + print(encrypt(private, "Hello World")) diff --git a/RSA/cuonghq_report.txt b/RSA/cuonghq_report.txt new file mode 100644 index 0000000..d91203f --- /dev/null +++ b/RSA/cuonghq_report.txt @@ -0,0 +1,16 @@ +# Mã hóa RSA +* Người thực hiện: Hoàng Quốc Cường * + +## Lý thuyết +### RSA là gì ? +- Là một hệ mã hóa bất đối xứng được phát triển bởi Ron Rivest, Adi Shamir, Leonard Adleman và được sử dụng rộng rãi trong công tác mã hóa và công nghệ chữ ký điện tử +- Hoạt động của RSA dựa trên 4 bước chính: + - Sinh khóa + - Chia sẻ key + - Mã hóa + - Giải mã +### Sinh khóa +- Khóa của RSA được sinh như sau: + - Chọn 2 số nguyên tố p và q + - Tính n = pq. (n sau được dùng làm modulus trong cả public key và private key) + - Tính số giả nguyên tố bằng hàm Carmichael: ** λ(n) = BCNN(λ(p), λ(q)) = BCNN(p − 1, q − 1) ** \ No newline at end of file diff --git a/SHA1/SHA-1-1.pdf b/SHA1/SHA-1-1.pdf new file mode 100644 index 0000000..ebed75d Binary files /dev/null and b/SHA1/SHA-1-1.pdf differ diff --git a/SHA1/SHA1.txt b/SHA1/SHA1.txt new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/SHA1/SHA1.txt @@ -0,0 +1 @@ + diff --git a/SHA1/sha1.py b/SHA1/sha1.py new file mode 100644 index 0000000..a0e1490 --- /dev/null +++ b/SHA1/sha1.py @@ -0,0 +1,68 @@ +def sha1(data): + bytes = "" + + h0 = 0x67452301 + h1 = 0xEFCDAB89 + h2 = 0x98BADCFE + h3 = 0x10325476 + h4 = 0xC3D2E1F0 + + for n in range(len(data)): + bytes+='{0:08b}'.format(ord(data[n])) + bits = bytes+"1" + pBits = bits + #pad until length equals 448 mod 512 + while len(pBits)%512 != 448: + pBits+="0" + #append the original length + pBits+='{0:064b}'.format(len(bits)-1) + + def chunks(l, n): + return [l[i:i+n] for i in range(0, len(l), n)] + + def rol(n, b): + return ((n << b) | (n >> (32 - b))) & 0xffffffff + + for c in chunks(pBits, 512): + words = chunks(c, 32) + w = [0]*80 + for n in range(0, 16): + w[n] = int(words[n], 2) + for i in range(16, 80): + w[i] = rol((w[i-3] ^ w[i-8] ^ w[i-14] ^ w[i-16]), 1) + + a = h0 + b = h1 + c = h2 + d = h3 + e = h4 + #Main loop + for i in range(0, 80): + if 0 <= i <= 19: + f = (b & c) | ((~b) & d) + k = 0x5A827999 + elif 20 <= i <= 39: + f = b ^ c ^ d + k = 0x6ED9EBA1 + elif 40 <= i <= 59: + f = (b & c) | (b & d) | (c & d) + k = 0x8F1BBCDC + elif 60 <= i <= 79: + f = b ^ c ^ d + k = 0xCA62C1D6 + + temp = rol(a, 5) + f + e + k + w[i] & 0xffffffff + e = d + d = c + c = rol(b, 30) + b = a + a = temp + + h0 = h0 + a & 0xffffffff + h1 = h1 + b & 0xffffffff + h2 = h2 + c & 0xffffffff + h3 = h3 + d & 0xffffffff + h4 = h4 + e & 0xffffffff + return '%08x%08x%08x%08x%08x' % (h0, h1, h2, h3, h4) + +print (sha1("hello world")) diff --git a/Vigenere/thachls_code_vigenere.py b/Vigenere/thachls_code_vigenere.py new file mode 100644 index 0000000..950f8d0 --- /dev/null +++ b/Vigenere/thachls_code_vigenere.py @@ -0,0 +1,253 @@ +##################################################################### +# VIGENERE CIPHER +# Function of this program: + # Senders input their message and the key + # Program will encrypt their messages into Vigenere code and send to the receiver + # Senders provide the key to the receiver to decrypt the text has been sent by senders + + +import math +import numpy as np +x_value = { + "Z": 0, "A": 1, "B": 2, "C": 3, "D": 4, "E": 5, + "F": 6, "G": 7, "H": 8, "I": 9, "J": 10, "K": 11, + "L": 12, "M": 13, "N": 14, "O": 15, "P": 16, "Q": 17, + "R": 18, "S": 19, "T": 20, "U": 21, "V": 22, "W":23, "X": 24, "Y": 25 +} + +y_value = { + "A": 26, "B": 25, "C": 24, "D": 23, "E": 22, + "F": 21, "G": 20, "H": 19, "I": 18, "J": 17, "K": 16, + "L": 15, "M": 14, "N": 13, "O": 12, "P": 11, "Q": 10, + "R": 9, "S": 8, "T": 7, "U": 6, "V": 5, "W":4, "X": 3, "Y": 2, "Z": 1, " ": 100 +} + + +reverse_x_value = { + 0: "Z", 1: "A", 2: "B", 3: "C", 4: "D", 5: "E", + 6: "F", 7: "G", 8: "H", 9: "I", 10: "J", 11: "K", + 12: "L", 13: "M", 14: "N", 15: "O", 16: "P", 17: "Q", + 18: "R", 19: "S", 20: "T", 21: "U", 22: "V", 23: "W", 24: "X", 25: "Y", 100: " " +} + +#this part of senders +def message_sender(): + # senders send their message + message = input("Please input your message: ") + message = message.upper() + # message belongs to y_value + message_y_value = [] + if len(message) <= 0: + print("Invalid message value, please enter your message again") + message = input("Please input your message: ") + message = message.upper() + for i in message: + message_y_value.append(i) + else: + for i in message: + message_y_value.append(i) + return message_y_value +message_y_value = message_sender() + + +def key_encrypt(): + #senders enter their keys + key = input("Please enter your key:") + key = key.upper() + # key belongs to x_value + key_x_value = [] + if len(key) <= 0: + print("Invalid key value, please enter your key again") + key = input("Please enter your key:") + key = key.upper() + for i in key: + key_x_value.append(i) + else: + for i in key: + key_x_value.append(i) + return key_x_value +key_x_value = key_encrypt() + +def convert_message_to_value(): + #convert message to value + message_sender_value = [] + for i in message_y_value: + message_sender_value.append(y_value[i]) + return message_sender_value +message_sender_value = convert_message_to_value() +def convert_to_key_value(): + #convert key to value + key_value = [] + for k in key_x_value: + key_value.append(x_value[k]) + return key_value +key_value = convert_to_key_value() + +def change_length_of_key_value(): + #change the length of key_value equal of length of message_sender_value + key_value_update = [] + if len(key_value) > len(message_sender_value): + key_value_update = key_value[:len(message_sender_value)] + else: + n = len(message_sender_value)/len(key_value) + n = math.ceil(n) + for i in range(n): + key_value_update += key_value + i += 1 + key_value_update = key_value_update[: len(message_sender_value)] + return key_value_update + + return key_value_update +key_value_update = change_length_of_key_value() + +encrypted_message_alphabet = [] +def encrypt_message_alphabet(): + #export encrypted message alphabet + for i in range(len(key_value_update)): + if message_sender_value[i] != 100: + value = key_value_update[i] - message_sender_value[i] + if value >= 0: + encrypted_message_alphabet.append(reverse_x_value[value]) + else: + value = 26 + value + encrypted_message_alphabet.append(reverse_x_value[value]) + else: + encrypted_message_alphabet.append(100) + + return encrypted_message_alphabet + + +def export_message_alphabet(): + user_message_encrypted ="" + for i in encrypted_message_alphabet: + if i == 100: + i = " " + user_message_encrypted += i + else: + user_message_encrypted += i + return user_message_encrypted + + +def sender_message(): + #this function for sender message + message_sender_value = convert_message_to_value() + key_value = convert_to_key_value() + key_value_update = change_length_of_key_value() + encrypted_message_alphabet = encrypt_message_alphabet() + user_message_encrypted = export_message_alphabet() + print("Your encrypted message: \n",user_message_encrypted) +sender_message() + + + +# this part of receivers +vigenere_value = { + "A": 0, "B": 1, "C": 2, "D": 3, "E": 4, + "F": 5, "G": 6, "H": 7, "I": 8, "J": 9, "K": 10, + "L": 11, "M": 12, "N": 13, "O": 14, "P": 15, "Q": 16, + "R": 17, "S": 18, "T": 19, "U": 20, "V": 21, "W":22, "X": 23, "Y": 24, "Z": 25, " ": 100 +} +reverse_vigenere_value = { + 0: "A", 1: "B", 2: "C", 3: "D", 4: "E", 5: "F", + 6: "G", 7: "H", 8: "I", 9: "J", 10: "K", 11: "L", + 12: "M", 13: "N", 14: "O", 15: "P", 16: "Q", 17: "R", + 18: "S", 19: "T", 20: "U", 21: "V", 22: "W", 23: "X", 24: "Y", 25: "Z", 100: " " +} + +def receiver_text(): + text = input("Please input your message: ") + text = text.upper() + # text belongs to vigenere_value + text_receiver = [] + if len(text) <= 0: + print("Invalid message value, please enter your message again") + else: + for i in text: + text_receiver.append(i) + return text_receiver +text_receiver = receiver_text() + +def receiver_key(): + #receiver enter key + key = input("Please enter your key:") + key = key.upper() + # key belongs to vigenere_value + key_receiver = [] + if len(key) <= 0: + print("Invalid key value, please enter your key again") + key = input("Please enter your key:") + key = key.upper() + for i in key: + key_receiver.append(i) + else: + for i in key: + key_receiver.append(i) + return key_receiver +key_receiver = receiver_key() + +def receiver_text_value(): + convert_receiver_text_value = [] + for i in text_receiver: + convert_receiver_text_value.append(vigenere_value[i]) + return convert_receiver_text_value +convert_receiver_text_value = receiver_text_value() + +def receiver_key_value(): + convert_receiver_key_value = [] + for i in key_receiver: + convert_receiver_key_value.append(vigenere_value[i]) + return convert_receiver_key_value +convert_receiver_key_value = receiver_key_value() + +def change_length_receiver_key_value(): + #change the length of receiver_key_value equal of length of receiver_text_value + receiver_key_value_update = [] + if len(convert_receiver_key_value) > len(convert_receiver_text_value): + receiver_key_value_update = convert_receiver_key_value[:len(convert_receiver_text_value)] + else: + n = len(convert_receiver_text_value)/len(convert_receiver_key_value) + n = math.ceil(n) + for i in range(n): + receiver_key_value_update += convert_receiver_key_value + i += 1 + receiver_key_value_update = receiver_key_value_update[: len(convert_receiver_text_value)] + return receiver_key_value_update + + return receiver_key_value_update +receiver_key_value_update = change_length_receiver_key_value() + +decrypted_receiver_message_alphabet = [] +def decrypt_message_alphabet(): + #export encrypted message alphabet + for i in range(len(receiver_key_value_update)): + if convert_receiver_text_value[i] != 100: + value = convert_receiver_text_value[i] - receiver_key_value_update[i] + if value >= 0: + decrypted_receiver_message_alphabet.append(reverse_vigenere_value[value]) + else: + value = 26 + value + decrypted_receiver_message_alphabet.append(reverse_vigenere_value[value]) + else: + decrypted_receiver_message_alphabet.append(" ") + + return decrypted_receiver_message_alphabet + +def export_receiver_message_alphabet(): + receiver_message_decrypted ="" + for i in decrypted_receiver_message_alphabet: + receiver_message_decrypted += i + return receiver_message_decrypted + +def receiver_message(): + #this function for receiver message + convert_receiver_text_value = receiver_text_value() + convert_receiver_key_value = receiver_key_value() + receiver_key_value_update = change_length_receiver_key_value() + decrypted_receiver_message_alphabet = decrypt_message_alphabet() + receiver_message_decrypted = export_receiver_message_alphabet() + print("Your message has been decrypted sucessful: \n",receiver_message_decrypted) +receiver_message() + + + + diff --git a/document/Using Github - Python Viet Nam.pdf b/document/Using Github - Python Viet Nam.pdf new file mode 100644 index 0000000..8ad9c83 Binary files /dev/null and b/document/Using Github - Python Viet Nam.pdf differ diff --git a/huanlv_report.txt b/huanlv_report.txt new file mode 100644 index 0000000..5e66c0b --- /dev/null +++ b/huanlv_report.txt @@ -0,0 +1,4 @@ +23/07-Hoàn thành code mô phỏng thuật toán Caesar +24/07-Tìm hiểu thuật toán des và viết một số hàm cần thiết cho thuật toán des +25/07-Hoàn thiện các hàm cần thiết, viết hàm sinh keys thuật toán des +26/07-Hoàn thiệt hàm mã hóa và giải mã thuật toán 3des \ No newline at end of file diff --git a/huongnm_code_Ripemd b/huongnm_code_Ripemd new file mode 100644 index 0000000..5efed8a --- /dev/null +++ b/huongnm_code_Ripemd @@ -0,0 +1,13 @@ +import hashlib +# from Crypto.Cipher import AES +# from Crypto.Hash import SHA256 +print("thuat toan ripemd160") +#thực hiện băm public key với SHA256 và ra kết quả RIPEMD – 160 +hash_256 = hashlib.sha256() +hash_str = "abcdefg" +hash_256.update(hash_str.encode('utf-8')) +hash_256_value = hash_256.hexdigest() +obj = hashlib.new('ripemd160', hash_256_value.encode('utf-8')) +ripemd_160_value = obj.hexdigest() +print("sha256:", hash_256_value) +print("ripemd160 :", ripemd_160_value) \ No newline at end of file diff --git a/huongnm_report.txt b/huongnm_report.txt new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/huongnm_report.txt @@ -0,0 +1 @@ + diff --git a/namth_code_sig.py b/namth_code_sig.py new file mode 100644 index 0000000..cc39d44 --- /dev/null +++ b/namth_code_sig.py @@ -0,0 +1,92 @@ +# Public Parameter +# Define generating prime number function +import random +from random import randint +def is_prime(num, test_count): + if num == 1: + return False + if test_count >= num: + test_count = num - 1 + for x in range(test_count): + val = randint(1, num - 1) + if pow(val, num-1, num) != 1: + return False + return True + +def generate_big_prime(n): + found_prime = False + while not found_prime: + p = randint(2**(n-1), 2**n) + if is_prime(p, 1000): + return p + +# Define finding primitive root function +def find_primitive_root(numberToFactor, arr=list()): + i = 2 + maximum = numberToFactor / 2 + 1 + while i < maximum: + if numberToFactor % i == 0: + return find_primitive_root(numberToFactor/i,arr + [i]) + i += 1 + return list(set(arr + [numberToFactor])) +# Set seed +n = 10 +# p is the prime +p = generate_big_prime(n) +print("[+] Generate prime number: {0}".format(p)) +# q is the primitve root of p-1 +q = find_primitive_root(p-1) +q = q[-1] +print("[+] Primitive root of p-1: {0}".format(q)) +# g is an integer order q modulus p +g = random.randint(1, p-1) +g = pow(g, q, p) +print("[+] Generate g number: {0}".format(g)) + +# Collect Input Data +print("""Enter Alice's Secret Key:""") +x1 = int(input("[+]Enter Alice's Secret Key: ")) +y1 = pow(g, x1, p) +print("Alice's Public Key: ",y1) +x1 = bytes(x1) +y1 = bytes(y1) + +print("""Enter Alice's Secret Key:""") +x2 = int(input("[+]Enter Bob's Secret Key: ")) +y2 = pow(g, x2, p) +print("Bob's Public Key: ",y2) +x2 = bytes(x2) +y2 = bytes(y1) + +# Alice choose a random value x # x1 +x = int(input("[+]Enter Alice's Secret Key: ")) +# Gerenate k (128 bit) by Hash funtion +from hashlib import blake2b +h = blake2b(y2, digest_size=16) +h.update(x) +k = h.hexdigest() +print("""K Value:""", k) + +# Generate k1, k2 +splitat = len(k) / 2 +k1 = k[:splitat] +k2 = k[splitat:] +print("""K1 Value:""",k1) +print("""K2 Value:""",k2) + +import nacl.utils +from nacl.public import PrivateKey, Box +print("""Enter Alice's Secret Message:""") +m = bytes(input("[+]Enter Alice's Secret Message: ")) + +# Alice Use k1 to Encrypt her Secret Message +c = k1.encrypt(m) + +# Alice Use k2 to Hash her Secret Message +from pyblake2 import blake2b +h = blake2b(k2, digest_size=16) +h.update(m) +r = h.hexdigest() + +# Alice Use R and C to compute S +s = x / ((r + x1) % q ) diff --git a/namth_report.txt b/namth_report.txt new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/namth_report.txt @@ -0,0 +1 @@ +