欢迎访问宙启技术站
智能推送

使用Python和Haskell实现的密码学算法

发布时间:2023-12-09 08:50:45

Python和Haskell都是常用于密码学算法实现的编程语言。它们都提供了丰富的库和函数,可以用于实现各种密码学算法。

以下是使用Python和Haskell实现的两个密码学算法的示例:凯撒密码和RSA算法。

1. 凯撒密码(Caesar Cipher):

Python实现:

def caesar_encrypt(plaintext, shift):
    ciphertext = ""
    for char in plaintext:
        if char.isalpha():
            ascii_offset = ord('a') if char.islower() else ord('A')
            shifted_char = chr((ord(char) - ascii_offset + shift) % 26 + ascii_offset)
            ciphertext += shifted_char
        else:
            ciphertext += char
    return ciphertext

def caesar_decrypt(ciphertext, shift):
    return caesar_encrypt(ciphertext, -shift)

plaintext = "Hello, World!"
shift = 3
ciphertext = caesar_encrypt(plaintext, shift)
print("Ciphertext:", ciphertext)
decrypted_plaintext = caesar_decrypt(ciphertext, shift)
print("Decrypted Plaintext:", decrypted_plaintext)

Haskell实现:

import Data.Char

caesarEncrypt :: String -> Int -> String
caesarEncrypt plaintext shift = map shiftChar plaintext
    where shiftChar char
            | isLower char = chr $ (ord char - ord 'a' + shift) mod 26 + ord 'a'
            | isUpper char = chr $ (ord char - ord 'A' + shift) mod 26 + ord 'A'
            | otherwise = char

caesarDecrypt :: String -> Int -> String
caesarDecrypt ciphertext shift = caesarEncrypt ciphertext (-shift)

plaintext :: String
plaintext = "Hello, World!"

shift :: Int
shift = 3

ciphertext :: String
ciphertext = caesarEncrypt plaintext shift
main :: IO ()
main = do
    putStrLn $ "Ciphertext: " ++ ciphertext
    let decryptedPlaintext = caesarDecrypt ciphertext shift
    putStrLn $ "Decrypted Plaintext: " ++ decryptedPlaintext

2. RSA算法:

Python实现:

import random
import math

def is_prime(n):
    if n == 2 or n == 3:
        return True
    if n < 2 or n % 2 == 0:
        return False
    for i in range(3, math.isqrt(n) + 1, 2):
        if n % i == 0:
            return False
    return True

def multiplicative_inverse(a, b):
    if b == 0:
        return (1, 0)
    else:
        q, r = divmod(a, b)
        s, t = multiplicative_inverse(b, r)
        return (t, s - q * t)

def generate_keys(p, q):
    if not (is_prime(p) and is_prime(q)):
        raise ValueError("Both p and q must be prime.")
    if p == q:
        raise ValueError("p and q cannot be the same number.")
    n = p * q
    phi = (p - 1) * (q - 1)
    e = random.randrange(1, phi)
    while math.gcd(phi, e) != 1:
        e = random.randrange(1, phi)
    d = multiplicative_inverse(e, phi)[0]
    return ((e, n), (d, n))

def encrypt(message, public_key):
    e, n = public_key
    return [pow(ord(char), e, n) for char in message]

def decrypt(ciphertext, private_key):
    d, n = private_key
    return ''.join([chr(pow(char, d, n)) for char in ciphertext])

p = 17
q = 11
public_key, private_key = generate_keys(p, q)
message = "Hello, World!"
encrypted_message = encrypt(message, public_key)
decrypted_message = decrypt(encrypted_message, private_key)
print("Encrypted Message:", encrypted_message)
print("Decrypted Message:", decrypted_message)

Haskell实现:

import System.Random
import Math.NumberTheory.Primes (isPrime)
import Math.NumberTheory.Moduli (isMultInvertible, multiplicativeInverse, (.^), n)
import Data.Char (ord, chr)

generatePrimes :: IO (Integer, Integer)
generatePrimes = do
    g <- newStdGen
    let p = head . filter isPrime $ randomRs (2, 100) g
    let q = head . filter (
 -> isPrime n && n /= p) $ randomRs (2, 100) g
    return (p, q)

generateKeys :: Integer -> Integer -> ((Integer, Integer), (Integer, Integer))
generateKeys p q =
    if not (isPrime p && isPrime q)
        then error "Both p and q must be prime."
        else if p == q
            then error "p and q cannot be the same number."
            else let n = p * q
                     phi = (p - 1) * (q - 1)
                     e = head . filter (\x -> isMultInvertible x phi) $ randomRs (2, phi) g
                     d = multiplicativeInverse e phi
                 in ((e, n), (d, n))
    where g = mkStdGen 1

encrypt :: String -> (Integer, Integer) -> [Integer]
encrypt message (e, n) = map (\c -> (n .^ ord c) mod n) message

decrypt :: [Integer] -> (Integer, Integer) -> String
decrypt ciphertext (d, n) = map (\c -> chr $ fromInteger $ (n .^ c) mod n) ciphertext

main :: IO ()
main = do
    (p, q) <- generatePrimes
    let (publicKey, privateKey) = generateKeys p q
        message = "Hello, World!"
        encryptedMessage = encrypt message publicKey
        decryptedMessage = decrypt encryptedMessage privateKey
    putStrLn $ "Encrypted Message: " ++ show encryptedMessage
    putStrLn $ "Decrypted Message: " ++ decryptedMessage

以上示例分别演示了凯撒密码和RSA加密算法在Python和Haskell中的实现。你可以根据需要选择合适的语言和算法进行使用和学习。