0% found this document useful (0 votes)
8 views12 pages

NSC 1

The document contains various code snippets for encryption and decryption algorithms including Caesar cipher, matrix operations for Hill cipher, and RSA encryption. It also includes key generation for Simple DES and its encryption and decryption processes. Additionally, it discusses modular arithmetic and matrix inverses in the context of cryptographic algorithms.

Uploaded by

durgamaripi2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views12 pages

NSC 1

The document contains various code snippets for encryption and decryption algorithms including Caesar cipher, matrix operations for Hill cipher, and RSA encryption. It also includes key generation for Simple DES and its encryption and decryption processes. Additionally, it discusses modular arithmetic and matrix inverses in the context of cryptographic algorithms.

Uploaded by

durgamaripi2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

1a) ceaser encrypt

# Input message and shift value


message = "Department of Information Technology"
shift_value = int(input("Enter the shift value: "))
# Encrypt the message
encrypted_message = ""
for char in message:
if char.isalpha(): # Check if the character is a letter
shift_base = 65 if char.isupper() else 97 # ASCII value for 'A' or 'a'
encrypted_message += chr((ord(char) - shift_base + shift_value) % 26 + shift_base)
else:
encrypted_message += char # Non-alphabetic characters remain unchanged
print("Encrypted Message:", encrypted_message)
—----------------------------------------------------------------------------------------------------------------------------
1b)
mat=[[2,3],[3,6]]
print(mat)
for rows in mat:
det=(mat[0][0]*mat[1][1]-mat[0][1]*mat[1][0])%26
print("det is")
print(det)
adj=[[mat[1][1],-mat[1][0]],[-mat[0][1],mat[0][0]]]
mod=[[ele%26 for ele in rows]for rows in adj]
print("adjoint")
for rows in mod:
print(rows)

—----------------------------------------------------------------------------------------------------------------------------

2a) caesar decrypt


# Ciphertext to decrypt
ciphertext = "RFIMZWFBFIFANXFPMFUFYSFR"

print("Brute-Force Decryption Results:")

# Try all possible shift values (0 to 25)


for shift_value in range(26):
decrypted_text = ""
for char in ciphertext:
if char.isalpha(): # Check if the character is a letter
shift_base = 65 if char.isupper() else 97 # ASCII value for 'A' or 'a'
decrypted_text += chr((ord(char) - shift_base - shift_value) % 26 + shift_base)
else:
decrypted_text += char # Non-alphabetic characters remain unchanged
print(f"Shift {shift_value}: {decrypted_text}")
—------------------------------------------------------------------------------------------------------------------------
2b)

mat=[[2,3],[3,6]]
print(mat)
for rows in mat:
det=(mat[0][0]*mat[1][1]-mat[0][1]*mat[1][0])%26
print("det is:")
print(det)
adj=[[mat[1][1],-mat[1][0]],[-mat[0][1],mat[0][0]]]
mod=[[ele%26 for ele in rows]for rows in adj]
print("adjoint: ")
for rows in mod:
print(rows)

det_mod_inv = pow(det, -1, 26)


print(f"Modular inverse of determinant: {det_mod_inv}")
inverse_matrix = [[(ele * det_mod_inv) % 26 for ele in row] for row in mod]
print("Inverse matrix mod 26:")
for row in inverse_matrix:
print(row)

—------------------------------------------------------------------------------------------------------------------------

3a)
p=7
q = 11
e=7
ciphertext = 37
n=p*q
phi_n = (p - 1) * (q - 1)

# Step 1: Find d using the modular inverse of e modulo phi(n) using brute force...
d=0
for i in range(1, phi_n):
if (e * i) % phi_n == 1:
d=i
break
# Step 2: Decrypt the ciphertext
plaintext = pow(ciphertext, d, n)
# Output the result
print(f"Decrypted plaintext: {plaintext}")

—--------------------------------------------------------------------------------------------------------------------------
4a)
p=3
q = 13
e=3
plaintext = 5
n=p*q
ciphertext = pow(plaintext, e, n)
print(f"Encrypted ciphertext: {ciphertext}")
p=3
q = 13
e=3
plaintext = 5
n=p*q
ciphertext = pow(plaintext, e, n)
print(f"Encrypted ciphertext: {ciphertext}")
—--------------------------------------------------------------------------------------------------------------------------
5a,6a,9a)
Subkey generation: ((**Recommended**))

key = 0b1110001111

def keyGen(key):
def leftShift(keyBits, positions=1):
return keyBits[positions:] + keyBits[:positions]

keyBits = list(map(int, f"{key:010b}"))


permKeyBits = [keyBits[i - 1] for i in P10table]
shiftedOnce = leftShift(permKeyBits[:5]) + leftShift(permKeyBits[5:])
shiftedTwice = leftShift(shiftedOnce[:5], 2) + leftShift(shiftedOnce[5:], 2)
subKey1 = int("".join(str(shiftedOnce[i - 1]) for i in P8table), 2)
subKey2 = int("".join(str(shiftedTwice[i - 1]) for i in P8table), 2)

print("SubKey1:", subKey1)
print("SubKey2:", subKey2)
print(f"Sub1: {bin(subKey1)}")
print(f"Sub2: {bin(subKey2)}")
return subKey1, subKey2

KeyLength = 10
P10table = [3, 5, 2, 7, 4, 10, 1, 9, 8, 6]
P8table = [6, 3, 7, 4, 8, 5, 10, 9]

keyGen(key)

—---------------------------------------------------------------or—---------------------------------------------------
key = 0b1110001110

def permute(key, table):


# Rearranges the bits of the key according to the given table
permuted_key = 0
for i, pos in enumerate(table):
if key & (1 << (KeyLength - pos)):
permuted_key |= (1 << (len(table) - 1 - i))
return permuted_key

def generate_keys(key):
def left_shift(bits, shifts):
return ((bits << shifts) & 0x3FF) | (bits >> (10 - shifts))

permuted_key = permute(key, P10table)


shifted_once = left_shift(permuted_key, 1)
shifted_twice = left_shift(shifted_once, 2)
K1 = permute(shifted_once, P8table)
K2 = permute(shifted_twice, P8table)
print("SubKey1:", bin(K1))
print("SubKey2:", bin(K2))
return K1, K2

KeyLength = 10
P10table = [3, 5, 2, 7, 4, 10, 1, 9, 8, 6]
P8table = [6, 3, 7, 4, 8, 5, 10, 9]

generate_keys(key)

—---------------------------------------------------------------------------------------------------------------------

7)​

import numpy as np
key = np.array([[2, 3], [3, 6]])
plaintext = "attack"
print(plaintext)

if len(plaintext) % 2 != 0:
plaintext += "x"

plainvector = [ord(char) - ord('a') for char in plaintext]

sb = []
for i in range(0, len(plaintext), 2):
first = (key[0][0] * plainvector[i] + key[0][1] * plainvector[i + 1]) % 26
second = (key[1][0] * plainvector[i] + key[1][1] * plainvector[i + 1]) % 26

sb.append(chr(first + ord('a')))
sb.append(chr(second + ord('a')))
print(''.join(sb))

—----------------------------------------------------------------------------------------------------------------------​
8)​
import numpy as np

def findinverse(a, m):


for x in range(m):
if (a * x) % m == 1:
return x
return -1

def main():
key = np.array([[2, 3], [3, 6]])
det = key[0][0] * key[1][1] - key[0][1] * key[1][0]
print("det is", det)
detinverse = findinverse(det, 26)
adjoint = np.zeros((2, 2), dtype=int)

adjoint[0][0] = key[1][1]
adjoint[0][1] = -key[0][1]
adjoint[1][0] = -key[1][0]
adjoint[1][1] = key[0][0]

inverse = np.zeros((2, 2), dtype=int)


for i in range(2):
for j in range(2):
inverse[i][j] = (adjoint[i][j] * detinverse) % 26
if inverse[i][j] < 0:
inverse[i][j] += 26

print("detinverse is", detinverse)


ciphertext = "FKMFIO"

if len(ciphertext) % 2 != 0:
ciphertext += "X"

plainvector = [ord(c) - ord('A') for c in ciphertext]

sb = []
for i in range(0, len(ciphertext), 2):
first = (inverse[0][0] * plainvector[i] + inverse[0][1] * plainvector[i + 1]) % 26
second = (inverse[1][0] * plainvector[i] + inverse[1][1] * plainvector[i + 1]) % 26

sb.append(chr(first + ord('A')))
sb.append(chr(second + ord('A')))

print("plain text is", ''.join(sb))

if __name__ == "__main__": #here there are two underscores check carefully


main()
—-------------------------------------------(or)---------------------------------------------------------------------------
mat=[[2,3],[3,6]]
det=(mat[0][0]*mat[1][1]-mat[0][1]*mat[1][0])%26

adj=[[mat[1][1],-mat[1][0]],[-mat[0][1],mat[0][0]]]
mod=[[ele%26 for ele in rows]for rows in adj]
det_mod_inv = pow(det, -1, 26)
print(f"Modular inverse of determinant: {det_mod_inv}")
inverse = [[(ele * det_mod_inv) % 26 for ele in row] for row in mod]

plaintext = "FKMFIO"
print(plaintext)

if len(plaintext) % 2 != 0:
plaintext += "x"

plainvector = [ord(char) - ord('A') for char in plaintext]

sb = []
for i in range(0, len(plaintext), 2):
first = (inverse[0][0] * plainvector[i] + inverse[0][1] * plainvector[i + 1]) % 26
second = (inverse[1][0] * plainvector[i] + inverse[1][1] * plainvector[i + 1]) % 26

sb.append(chr(first + ord('A')))
sb.append(chr(second + ord('A')))

print(''.join(sb))


—---------------------------------------------------------------------------------------------------------------------------

5b)...Simple des encryption

# Necessary permutation tables


IPtable = (2, 6, 3, 1, 4, 8, 5, 7)
FPtable = (4, 1, 3, 5, 7, 2, 8, 6)
P10table = (3, 5, 2, 7, 4, 10, 1, 9, 8, 6)
P8table = (6, 3, 7, 4, 8, 5, 10, 9)
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)

# Permutation function
def perm(inputByte, permTable):
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

# Initial permutation
def ip(inputByte):
return perm(inputByte, IPtable)

# Final permutation
def fp(inputByte):
return perm(inputByte, FPtable)

# Swap nibbles
def swapNibbles(inputByte):
return (inputByte << 4 | inputByte >> 4) & 0xff
# Key Generation
def keyGen(key):
def leftShift(keyBitList):
shiftedKey = [None] * 10
shiftedKey[0:9] = keyBitList[1:10]
shiftedKey[4] = keyBitList[0]
shiftedKey[9] = keyBitList[5]
return shiftedKey

keyList = [(key & 1 << i) >> i for i in reversed(range(10))]


permKeyList = [None] * 10
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)

# Feistel function
def fk(subKey, inputData):
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

# Encrypt function
def encrypt(key, plaintext):
data = fk(keyGen(key)[0], ip(plaintext))
return fp(fk(keyGen(key)[1], swapNibbles(data)))

# Example usage
plaintext = 0b10101010
key = 0b1110001110
cipher = encrypt(key, plaintext)
print(f"Plaintext: {bin(plaintext)}")
print(f"Ciphertext: {bin(cipher)}")
—---------------------------------------------------------------------------------------------------------
6 b) s-des decrypt

# Necessary permutation tables


IPtable = (2, 6, 3, 1, 4, 8, 5, 7)
FPtable = (4, 1, 3, 5, 7, 2, 8, 6)
P10table = (3, 5, 2, 7, 4, 10, 1, 9, 8, 6)
P8table = (6, 3, 7, 4, 8, 5, 10, 9)
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)

# Permutation function
def perm(inputByte, permTable):
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

# Initial permutation
def ip(inputByte):
return perm(inputByte, IPtable)

# Final permutation
def fp(inputByte):
return perm(inputByte, FPtable)

# Swap nibbles
def swapNibbles(inputByte):
return (inputByte << 4 | inputByte >> 4) & 0xff

# Key Generation
def keyGen(key):
def leftShift(keyBitList):
shiftedKey = [None] * 10
shiftedKey[0:9] = keyBitList[1:10]
shiftedKey[4] = keyBitList[0]
shiftedKey[9] = keyBitList[5]
return shiftedKey

keyList = [(key & 1 << i) >> i for i in reversed(range(10))]


permKeyList = [None] * 10
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)

# Feistel function
def fk(subKey, inputData):
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

# Decrypt function
def decrypt(key, ciphertext):
data = fk(keyGen(key)[1], ip(ciphertext))
return fp(fk(keyGen(key)[0], swapNibbles(data)))

# Example usage for decryption


ciphertext = 0b11001010 # Some encrypted ciphertext
key = 0b1110001110 # The key used for encryption
decrypted_text = decrypt(key, ciphertext)
print(f"Ciphertext: {bin(ciphertext)}")
print(f"Decrypted text: {bin(decrypted_text)}")

***Not recommended***

def simpleEncrypt(plaintext, subKey1, subKey2):


block = f"{plaintext:08b}"
left = int(block[:4], 2)
right = int(block[4:], 2)
left1 = left ^ (subKey1 & 0b1111)
right1 = right
newLeft = right1
newRight = left1
left2 = newLeft ^ (subKey2 & 0b1111)
right2 = newRight
encrypted = (left2 << 4) | right2
return encrypted

def simpleDecrypt(ciphertext, subKey1, subKey2):


block = f"{ciphertext:08b}"
left = int(block[:4], 2)
right = int(block[4:], 2)
left1 = left ^ (subKey2 & 0b1111)
right1 = right
newLeft = right1
newRight = left1
left2 = newLeft ^ (subKey1 & 0b1111)
right2 = newRight
decrypted = (left2 << 4) | right2
return decrypted

plaintext = 0b10101010
subKey1 = 0b11101110
subKey2 = 0b11001111

ciphertext = simpleEncrypt(plaintext, subKey1, subKey2)


decrypted = simpleDecrypt(ciphertext, subKey1, subKey2)
print(f"Plaintext: {bin(plaintext)}")
print(f"Ciphertext: {bin(ciphertext)}")
print(f"Decrypted: {bin(decrypted)}")
print(f"SubKey1: {bin(subKey1)}")
print(f"SubKey2: {bin(subKey2)}")

You might also like