Wednesday, 9 January 2019

Python Program to implement playfair (CSS)


        ip = input("Enter the keyword: ")
    ip2 = input("Enter Your message: ")
    ip = list(ip)
    ip2 = list(ip2)

    keyword = []
    for x in ip:
        if x not in keyword:
            keyword.extend(x)

    key_list = [chr(x) for x in range(97, 97+26)
                if chr(x) not in keyword]
    key_list = keyword + key_list
    key_list = [x.upper() for x in key_list]
    key_list.remove('J')

    ip2 = [x.upper() for x in ip2]
    for n, i in enumerate(ip2):
        if i == 'J':
            ip2[n] = 'I'
    if len(ip2) % 2 != 0:
        ip2.extend('X')

    n = 0
    message = []
    while n < len(ip2)-1:
        if ip2[n] == ip2[n+1]:
            message.extend(ip2[n])
            message.extend('X')
            message.extend(ip2[n+1])
            message.extend('X')
        else:
            message.extend(ip2[n])
            message.extend(ip2[n+1])
        n += 2
    # print(message)

    n = 0
    matrix = {}
    for i in range(1, 6):
        for j in range(1, 6):
            matrix[key_list[n]] = [i, j]
            n += 1
    # print(matrix)

    n = 0
    output = []
    while n <= len(message)-1:
        a = matrix[message[n]]
        b = matrix[message[n+1]]
        if a[0] == b[0]:
            a[0] += 1
            b[0] += 1
        if a[1] == b[1]:
            a[1] += 1
            b[1] += 1

        if a[0] > 5:
            a[0] = 1
        if a[1] > 5:
            a[1] = 1
        if b[0] > 5:
            b[0] = 1
        if b[1] > 5:
            b[1] = 1

        if a[0] == b[0] or a[1] == b[1]:
            output.append([a[0], b[1]])
            output.append([a[1], b[0]])

        if a[0] != b[0] and a[1] != b[1]:
            output.append([a[0], b[1]])
            output.append([a[1], b[0]])

        n += 2

    k = list(matrix.keys())
    v = list(matrix.values())
    cipher_text = ""
    for i in output:
        cipher_text += k[v.index(i)]
    print("The Encrypted text is: ", cipher_text)


    '''
    Output:

    codept@codept-04 ~/Desktop/exp2 $ python3 playfair.py 
    Enter the keyword: keyword
    Enter Your message: playfair
    The Encrypted text is:  SHBMIEFN
    '''

No comments:

Post a Comment