SCE-Cryptography-Experiment

本文最后更新于:2023年6月19日 晚上

生成 RSA 大素数对

1
2
3
4
5
6
7
8
9
10
11
12
13
14
from Crypto.PublicKey import RSA
RSAkey = RSA.generate(1024)
"""
RsaKey(n=135828718287577504794345019580082927233382329800436650769778319130905210891299413615216512376642256926
81082083849207511789369113995656114347658628181817364203829151160294408679251739590425386713208320533180799940969738619
5247179226323919349310987779260954782675652897977451878557940738099185187754664490831243, e=65537, d=121948850024277284
31419291319547857604730482453358702002370807784400357979224037562169979688178632524487768280722147336522673889062734116
12091236526264756659745917698038449276833478093929539387457070306648475772351712570431776434737921224077076846006461005
1801442191171153628914016094739518761772299602223169, p=106966107287469170015624352521638251586863407906376169924940482
70893593178051022233452907429273165871602433433280712262828660157650519133674850464955099769, q=12698294976981883899887
05757908736918629112987783691507779835783942064221972829430441724076915068135969878213856988519323444267214248422535888
1222134150947, u=748951926994679052549581035821877331925827771100922884099976839588394981271357878319645686189368446921
7133192361022681583376512653412786705315289991596596)
"""

注意这个 Crypto 库一般情况在导入的时候都会出错,有几种情况,我介绍一下我遇到的,就是我之前安装了 pycrypto 这个库,但是这个库最新的一版是 2014 年,已经不兼容了,当我尝试 uninstall 它时,报错
ERROR: Cannot uninstall 'pycrypto'. It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall.
这时候,我们必须全局搜索 pycrypto,并手动删除那个文件夹
然后在cmd 下安装
pip install pycryptodome --user

我也不知道为什么必须在 cmd 下安装,一开始用 powershell 安装的时候我在 Python37 文件夹中找不到它…

Fermat 定理检验素数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
def FermatPrimalityTest(m,k):
"""
m:给定奇整数
k:安全参数,重复K次
"""

if m%2==0:
return False
for i in range(k):
a = random.randint(2,m-2)
g = gmpy2.gcd(a,m)
if g==1:
r = gmpy2.powmod(a,m-1,m)
if r ==1:
continue
else:
return False
else:
return False
return True

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!