西电现代密码学实验三
1.代码
import mathdef compute():P = 1009Q = 3643TOTIENT = (P - 1) * (Q - 1)numunconcealedp = count_all_unconcealed(P)numunconcealedq = count_all_unconcealed(Q)minunconcealedp = min(numunconcealedp)minunconcealedq = min(numunconcealedq)ans = sum(e for e in range(TOTIENT) ifnumunconcealedp[e % (P - 1)] == minunconcealedp andnumunconcealedq[e % (Q - 1)] == minunconcealedq)return str(ans)def count_all_unconcealed(prime):result = []for e in range(prime - 1):if math.gcd(e, prime - 1) == 1:result.append(count_unconcealed(prime, e))else:result.append(10**20) return resultdef count_unconcealed(modulus, e):result = 0for m in range(modulus):if pow(m, e, modulus) == m:result += 1return resultif __name__ == "__main__":print(compute())
2.代码
from Crypto.Random import random
import binasciidef invmod(a, n):t = 0newt = 1r = nnewr = awhile newr != 0:q = r // newr(t, newt) = (newt, t - q * newt)(r, newr) = (newr, r - q * newr)if r > 1:raise Exception('unexpected')if t < 0:t += nreturn tsmallPrimes = [2, 3, 5, 7, 11, 13, 17, 19]def hasSmallPrimeFactor(p):for x in smallPrimes:if p % x == 0:return Truereturn Falsedef isProbablePrime(p, n):for i in range(n):a = random.randint(1, p-1)if pow(a, p - 1, p) != 1:return Falsereturn Truedef getProbablePrime(bitcount):while True:p = random.randint(2**(bitcount - 1), 2**bitcount - 1)if not hasSmallPrimeFactor(p) and isProbablePrime(p, 5):return pdef genKey(keysize):e = 3bitcount = (keysize + 1) // 2 + 1p = 7while (p - 1) % e == 0:p = getProbablePrime(bitcount)q = pwhile q == p or (q - 1) % e == 0:q = getProbablePrime(bitcount)n = p * qet = (p - 1) * (q - 1)d = invmod(e, et)pub = (e, n)priv = (d, n)return (pub, priv)def encryptnum(pub, m):(e, n) = pubif m < 0 or m >= n:raise ValueError(str(m) + ' out of range')return pow(m, e, n)def decryptnum(priv, c):(d, n) = privif c < 0 or c >= n:raise ValueError(str(c) + ' out of range')return pow(c, d, n)# Drops leading zero bytes.
def bytestonum(s):return int.from_bytes(s, byteorder='big')def numtobytes(k):return k.to_bytes((k.bit_length() + 7) // 8, byteorder='big')def encryptbytes(pub, mbytes):m = bytestonum(mbytes)c = encryptnum(pub, m)cbytes = numtobytes(c)return cbytesdef decryptbytes(priv, cbytes):c = bytestonum(cbytes)m = decryptnum(priv, c)mstr = numtobytes(m)return mstrif __name__ == '__main__':pub, priv = genKey(128)m = b'test'c = encryptbytes(pub, m)m2 = decryptbytes(priv, c)if m != m2:raise Exception(str(m) + ' != ' + str(m2))print("加密解密成功!原始数据:", m, "解密后:", m2)
