# SHA-256 Hashing
import hashlib
# Function to hash a string using SHA-256
def sha256_hash_string(input_string):
# Create a new sha256 hash object
sha256 = hashlib.sha256()
# Update the hash object with the bytes of the input string
sha256.update(input_string.encode('utf-8'))
# Get the hexadecimal representation of the hash
hex_digest = sha256.hexdigest()
return hex_digest
# Example usage
input_string = "Hello, world!"
hash_result = sha256_hash_string(input_string)
print(f"SHA-256 hash of '{input_string}': {hash_result}")
#RSA
import math
# step 1
p = 3
q = 7
# step 2
n = p*q
print("n =", n)
# step 3
phi = (p-1)*(q-1)
# step 4
e = 2
while(e<phi):
if (math.gcd(e, phi) == 1):
break
else:
e += 1
print("e =", e)
# step 5
k = 2
d = ((k*phi)+1)/e
print("d =", d)
print(f'Public key: {e, n}')
print(f'Private key: {d, n}')
# plain text
msg = 11
print(f'Original message:{msg}')
# encryption
C = pow(msg, e)
C = math.fmod(C, n)
print(f'Encrypted message: {C}')
# decryption
M = pow(C, d)
M = math.fmod(M, n)
print(f'Decrypted message: {M}')
#Vernam
def Vernam(text, key):
cipher_text = ''
for i in range(len(text)):
character = chr(ord(text[i]) ^ ord(key[i]))
cipher_text += character
return cipher_text
if __name__ == "__main__":
text = "My Secret text"
key = 'mjcipuqszsymzp' # Ensure key is at least as long as text
cipher_text = Vernam(text, key)
print("Cipher text:", repr(cipher_text))
original_text = Vernam(cipher_text, key)
print("Original text:", original_text)
#Vignere
def vigenere(text, key, mode='encrypt'):
key = (key * (len(text) // len(key) + 1))[:len(text)]
res = []
for t, k in zip(text, key):
if mode == 'encrypt':
res.append(chr((ord(t) + ord(k) - 2 * ord('A')) % 26 + ord('A')))
else:
res.append(chr((ord(t) - ord(k) + 26) % 26 + ord('A')))
return ''.join(res)
if __name__ == "__main__":
text = "HELLOVIGENERECIPHER"
key = "KEY"
cipher_text = vigenere(text, key, mode='encrypt')
print("Cipher Text: ", cipher_text)
original_text = vigenere(cipher_text, key, mode='decrypt')
print("Original Text: ", original_text)
#rc4
def rc4(key, data):
S = list(range(256))
j = 0
out = []
# Key scheduling algorithm (KSA)
for i in range(256):
j = (j + S[i] + key[i % len(key)]) % 256
S[i], S[j] = S[j], S[i]
# Pseudo-random generation algorithm (PRGA)
i = j = 0
for char in data:
i = (i + 1) % 256
j = (j + S[i]) % 256
S[i], S[j] = S[j], S[i]
out.append(char ^ S[(S[i] + S[j]) % 256])
return bytes(out)
# Main program
if __name__ == "__main__
":
key = b'secretkey' # Key for encryption/decryption
plain_text = "This is a secret message."
# Convert plaintext to bytes
plain_text_bytes = plain_text.encode('utf-8')
# Encrypt
encrypted = rc4(key, plain_text_bytes)
print(f"Encrypted text: {encrypted}")
# Decrypt (RC4 encryption and decryption are symmetric)
decrypted = rc4(key, encrypted)
print(f"Decrypted text: {decrypted.decode('utf-8')}")
#hill cipher
keyMatrix = [[0] * 3 for i in range(3)]
messageVector = [[0] for i in range(3)]
cipherMatrix = [[0] for i in range(3)]
def getKeyMatrix(key):
k = 0
for i in range(3):
for j in range(3):
keyMatrix[i][j] = ord(key[k]) % 65
k += 1
def encrypt(messageVector):
for i in range(3):
for j in range(1):
cipherMatrix[i][j] = 0
for x in range(3):
cipherMatrix[i][j] += (keyMatrix[i][x] *
messageVector[x][j])
cipherMatrix[i][j] = cipherMatrix[i][j] % 26
def HillCipher(message, key):
getKeyMatrix(key)
for i in range(3):
messageVector[i][0] = ord(message[i]) % 65
encrypt(messageVector)
CipherText = []
for i in range(3):
CipherText.append(chr(cipherMatrix[i][0] + 65))
print("Ciphertext: ", "".join(CipherText))
def main():
message = "ACT"
key = "GYBNQKURP"
HillCipher(message, key)
if __name__ == "__main__":
main()
#feistel
def xor_strings(s1, s2):
return ''.join(chr(ord(a) ^ ord(b)) for a, b in zip(s1, s2))
def feistel_round(left, right, key):
new_left = right
new_right = xor_strings(left, xor_strings(right, key))
return new_left, new_right
def feistel(text, keys, encrypt=True):
left, right = text[:len(text)//2], text[len(text)//2:]
if not encrypt:
keys = reversed(keys)
for key in keys:
left, right = feistel_round(left, right, key)
return left + right
if __name__ == "__main__":
text = "HELLO123" # Text length should be even
keys = ["K1", "K2", "K3", "K4"] # Example round keys
# Ensure text length is even
if len(text) % 2 != 0:
text += "X"
encrypted_text = feistel(text, keys, encrypt=True)
print("Encrypted Text:", encrypted_text)
decrypted_text = feistel(encrypted_text, keys, encrypt=False)
print("Decrypted Text:", decrypted_text)
#aes
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from Crypto.Random import get_random_bytes
def aes_encrypt(plaintext, key):
cipher = AES.new(key, AES.MODE_CBC)
ciphertext = cipher.encrypt(pad(plaintext.encode('utf-8'), AES.block_size))
return cipher.iv + ciphertext
def aes_decrypt(ciphertext, key):
iv = ciphertext[:AES.block_size]
cipher = AES.new(key, AES.MODE_CBC, iv)
plaintext = unpad(cipher.decrypt(ciphertext[AES.block_size:]), AES.block_size)
return plaintext.decode('utf-8')
if __name__ == "__main__":
plaintext = "Hello, AES!"
key = get_random_bytes(16) # AES-128 key (16 bytes)
ciphertext = aes_encrypt(plaintext, key)
print("Ciphertext:", ciphertext)
decrypted_text = aes_decrypt(ciphertext, key)
print("Decrypted Text:", decrypted_text)
#2 des
from Crypto.Cipher import DES
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad, unpad
def des_encrypt(plaintext, key):
cipher = DES.new(key, DES.MODE_ECB)
return cipher.encrypt(plaintext)
def des_decrypt(ciphertext, key):
cipher = DES.new(key, DES.MODE_ECB)
return cipher.decrypt(ciphertext)
def double_des_encrypt(plaintext, key1, key2):
padded_plaintext = pad(plaintext, DES.block_size)
encrypted = des_encrypt(padded_plaintext, key1)
encrypted = des_encrypt(encrypted, key2)
return encrypted
def double_des_decrypt(ciphertext, key1, key2):
decrypted = des_decrypt(ciphertext, key2)
decrypted = des_decrypt(decrypted, key1)
return unpad(decrypted, DES.block_size)
if __name__ == "__main__":
plaintext = b"Hello, 2DES!" # Example plaintext (as bytes)
key1 = get_random_bytes(8) # First DES key (8 bytes)
key2 = get_random_bytes(8) # Second DES key (8 bytes)
ciphertext = double_des_encrypt(plaintext, key1, key2)
print("Ciphertext:", ciphertext)
decrypted_text = double_des_decrypt(ciphertext, key1, key2)
print("Decrypted Text:", decrypted_text.decode('utf-8'))
#ceaser
def encrypt(text, shift):
result = ""
# traverse text
for i in range(len(text)):
char = text[i]
# Encrypt uppercase characters
if char.isupper():
result += chr((ord(char) + shift - 65) % 26 + 65)
# Encrypt lowercase characters
elif char.islower():
result += chr((ord(char) + shift - 97) % 26 + 97)
# Encrypt digits
elif char.isdigit():
result += chr((ord(char) + shift - 48) % 10 + 48)
# Encrypt special characters
else:
result += char
return result
def decrypt(text, shift):
return encrypt(text, -shift)
# Example usage
text = "Hello, World! 123"
shift = 4
encrypted = encrypt(text, shift)
decrypted = decrypt(encrypted, shift)
print(f"Text: {text}")
print(f"Shift: {shift}")
print(f"Encrypted: {encrypted}")
print(f"Decrypted: {decrypted}")