Skip to content

RSA encryption algorithm

Dương Tiến Vinh edited this page Jun 5, 2022 · 3 revisions

1. Generate keys:

Code for Extended Euclid can be found in file crypto.py

Code implementation
def generateKeys(p, q):
    n = calculate_n(p, q)
    phi_n = calculate_phi_n(q, p)
    u, x, d = 0, 0, 0
    e = 0
    while u != 1:
        e = random.randint(2, phi_n - 1)
        u, x, d = GCD(phi_n, e)
        if d < 0:
            d = phi_n + d
    return n, e, d

2. Encryption:

Code implementation
def encrypt(
    imgPath,
    e=None,
    n=None,
    publicKeyPath=None,
    imgEncryptedSaveDst="encode_img.png",
    quotientSaveDst="quotient.txt",
):
    if not publicKeyPath and not e and not n:
        raise Exception("Public key is missing")
    # e, n directly passed into function has more priority than text file
    if publicKeyPath and not e and not n:
        publicKey = readFile(publicKeyPath)
        n, e = map(int, publicKey.split(" "))

    if not e or not n and not publicKeyPath:
        raise Exception("Public key is missing.")

    if not os.path.exists(imgPath):
        raise Exception("Image path is not exist")

    img = cv2.imread(imgPath)

    f = open(quotientSaveDst, "w")
    for i in range(3):
        for j in range(img.shape[0]):
            for l in range(img.shape[1]):
                pixel = img[j, l, i]
                remainder1 = powermod(pixel, e, n)
                remainder2 = powermod(remainder1, 1, 256)
                quotient = int(remainder1 / 256)
                img[j, l, i] = remainder2
                f.write(str(quotient) + " ")
    f.close()
    cv2.imwrite(imgEncryptedSaveDst, img)
    return img

3. Decryption:

Code implementation
def decrypt(
    imgEncryptedPath,
    d=None,
    n=None,
    privateKeyPath=None,
    imgDecryptedSaveDst="decode_img.png",
    quotientPath="quotient.txt",
):
    if not privateKeyPath and not d and not n:
        raise Exception("Private key is missing")
    # d, n directly passed into function has more priority than text file
    if privateKeyPath and not d and not n:
        private_key = readFile(privateKeyPath)
        d, n = map(int, private_key.split(" "))

    if not os.path.exists(imgEncryptedPath):
        raise Exception("Image path is not exist")

    if not os.path.exists(quotientPath):
        raise Exception("Quotient path is not exist")

    img = cv2.imread(imgEncryptedPath)
    quotient = readFile(quotientPath)
    list_quotient = quotient.split(" ")

    index = 0
    for i in range(3):
        for j in range(img.shape[0]):
            for l in range(img.shape[1]):
                pixel = img[j, l, i]
                c = pixel + int(list_quotient[index]) * 256
                img[j, l, i] = powermod(c, d, n)
                index = index + 1
    cv2.imwrite(imgDecryptedSaveDst, img)
    return img
Clone this wiki locally