PKCS1_RSA
文章目錄
- 3. Key Types
- 公鑰質(zhì)數(shù)E
- 生成隨機(jī)大質(zhì)數(shù)p和q
- 判斷素?cái)?shù)
- 求最小公倍數(shù)L
- 求私鑰質(zhì)數(shù)D
- PyCryptodome generate()
- 4. Data Conversion Primitives
- 5. Cryptographic Primitives
- 5.1. Encryption and Decryption Primitives
- 5.1.1 RSAEP
- 5.1.2 RSADP
- 5.2. Signature and Verification Primitives
- 5.2.1. RSASP1
- 5.2.2. RSAVP1
- 6. Overview of Schemes
- 加解密示例
- OpenSSL接口
- 接口
- 命令
- 實(shí)現(xiàn)
- 參考資料
RSA的RFC文檔已經(jīng)更新了很多次,截至本文(2023.1),最新的文檔是 RFC 8017: PKCS #1: RSA Cryptography Specifications Version 2.2。在頁面開頭搜索關(guān)鍵詞Obsolete可以鏈接到歷史文檔。應(yīng)用較廣的版本是 RFC 2313: PKCS #1: RSA Encryption Version 1.5
也可以參考NIST.SP.800-56B和FIPS 186-4, Digital Signature Standard (DSS) | CSRC (nist.gov)。
PKCS, The Public-Key Cryptography Standards,涉及多個(gè)標(biāo)準(zhǔn),其中PKCS #1為RSA的標(biāo)準(zhǔn),可以在RFC官網(wǎng)搜索PKCS查閱。
簡(jiǎn)介:
- 命名取自三位發(fā)明者的姓氏字母Ron Rivest、Adi Shamir、Leonard Adleman;
- 官網(wǎng):https://rsa.com/
- 1983年申請(qǐng)專利,現(xiàn)已過期,所以可以商用;
- 公鑰密碼基于數(shù)學(xué)困難問題保證機(jī)密性,RSA的基礎(chǔ)是,大整數(shù)質(zhì)因數(shù)分解十分困難;
- RSA的實(shí)現(xiàn)通常會(huì)用到Base64,主要是為了防止產(chǎn)生亂碼;
- RSA的密鑰長度、密文和簽名長度與模量n一致,比如2048 bits(256 bytes),參考FIPS記為nlen,RSA的安全強(qiáng)度與模量n的位數(shù)相關(guān)聯(lián);
- 2017年根據(jù)ECRYPT報(bào)告,建議長度不少于2048 bits;
- FIPS 186-4簽名標(biāo)準(zhǔn)中為1024, 2048 和3072 bits;
- 簽名和解密(基于私鑰)比驗(yàn)簽和加密(基于公鑰)慢;
- …
文章與PKCS一致。
3. Key Types
RSA Public Key:
- n, the RSA modulus(模量), a positive integer
- e, the RSA public exponent, a positive integer
RSA Private Key:
- n, the RSA modulus, a positive integer, the same as in the corresponding RSA public key.
- d, the RSA private exponent, a positive integer
其中,私鑰在RFC 8017中還有第二種表示法,參數(shù)很多,感興趣的可查看原文檔。
密鑰生成步驟參考FIPS 186-4
- B.3.1 Criteria for IFC Key Pairs
- B.3.3 Generation of Random Primes that are Probably Prime
IFC: Integer Factorization Cryptography
術(shù)語:
- LCM, Least Common Multiple, 最小公倍數(shù)。
- GCM, Greatest Common , 最大公約數(shù)。
公鑰質(zhì)數(shù)E
根據(jù)FIPS 186-4 B.3.1 1(b),E使用滿足以下條件的默認(rèn)值即可:
2^16 < e < 2^256 65537 == 2^16 + 1 # default若E采用隨機(jī)值,則性能不可控。
生成隨機(jī)大質(zhì)數(shù)p和q
需要使用偽隨機(jī)數(shù)生成器生成這兩個(gè)大質(zhì)數(shù),
- (p-1)和(q-1)分別與e互素( relatively prime to e)
- len§ = len(q) = nlen/2
- 2(nlen-1)/2 <= p <= 2nlen/2 - 1 == 2len§ - 1, q一致
- p和q差值 > 2nlen/2-100
N = p x q,生成N后丟棄p和q。
生成方法有兩種:
判斷素?cái)?shù)
方法有很多,FIPS 186-4 C.3 PROBABILISTIC PRIMALITY TESTS提供了以下方法:
- Miller-Rabin Probabilistic Primality Test
- Enhanced Miller-Rabin Probabilistic Primality Test
- (General) Lucas Probabilistic Primality Test
其它還有費(fèi)馬素性檢測(cè)(Fermat Primality Test)等。
參考代碼:\Crypto\Math\Primality.py
求最小公倍數(shù)L
L = LCM(p-1, q-1)
GCD(E, L) == 1,保證一定存在私鑰中的D;
求私鑰質(zhì)數(shù)D
2nlen/2 < D < L,若不滿足需要重新生成p和q。
E x D mod L == 1,保證可以解密還原明文。
即:D = E-1mod L
等價(jià)于:1==(ED) mod L
Miracl庫的xgcd可以用來求模逆:
xgcd(x, p, x, x, x,); // x = 1/x mod p (p is prime)PyCryptodome generate()
\Crypto\PublicKey\RSA.py
def generate(bits, randfunc, e=65537):# ...d = n = Integer(1)e = Integer(e)while n.size_in_bits() != bits and d < (1 << (bits // 2)):# Generate the prime factors of n: p and q.# By construciton, their product is always# 2^{bits-1} < p*q < 2^bits.size_q = bits // 2size_p = bits - size_qmin_p = min_q = (Integer(1) << (2 * size_q - 1)).sqrt()if size_q != size_p:min_p = (Integer(1) << (2 * size_p - 1)).sqrt()def filter_p(candidate):return candidate > min_p and (candidate - 1).gcd(e) == 1p = generate_probable_prime(exact_bits=size_p,randfunc=randfunc,prime_filter=filter_p)min_distance = Integer(1) << (bits // 2 - 100)def filter_q(candidate):return (candidate > min_q and(candidate - 1).gcd(e) == 1 andabs(candidate - p) > min_distance)q = generate_probable_prime(exact_bits=size_q,randfunc=randfunc,prime_filter=filter_q)n = p * qlcm = (p - 1).lcm(q - 1)d = e.inverse(lcm)4. Data Conversion Primitives
- I2OSP - Integer-to-Octet-String == long_to_bytes
- OS2IP - Octet-String-to-Integer == bytes_to_long
5. Cryptographic Primitives
源碼參考PyCryptodome
5.1. Encryption and Decryption Primitives
公鑰加密,私鑰解密。
5.1.1 RSAEP
RSA Encryption Primitive
def RSAEP ((n, e), m):# an integer between 0 and n - 1return c = m**e % n# pycryptodome \Crypto\PublicKey\RSA.py def _encrypt(self, plaintext):if not 0 <= plaintext < self._n:raise ValueError("Plaintext too large")return int(pow(Integer(plaintext), self._e, self._n))5.1.2 RSADP
RSA Decryption Primitive
# def RSADP (K, c):# K: one of the 2 forms of private key def RSADP((n,d), c):return m = c**d % ndef RSADP((p, q, dP, dQ, qInv, r_i, d_i, t_i), c):m_1 = c**dP % p m_2 = c**dQ % qif u > 2:m_i = c**(d_i) % r_i # i = 3, ..., uh = (m_1 - m_2) * qInv % pm = m_2 + q * hif u > 2:R = r_1for i in range(3, u+1):R = R * r_(r-1)h = (m_i - m) * t_i % r_im = m + R * h.return m# pycryptodome \Crypto\PublicKey\RSA.py def _decrypt(self, ciphertext):if not 0 <= ciphertext < self._n:raise ValueError("Ciphertext too large")if not self.has_private():raise TypeError("This is not a private key")# Blinded RSA decryption (to prevent timing attacks):# Step 1: Generate random secret blinding factor r,# such that 0 < r < n-1r = Integer.random_range(min_inclusive=1, max_exclusive=self._n)# Step 2: Compute c' = c * r**e mod ncp = Integer(ciphertext) * pow(r, self._e, self._n) % self._n# Step 3: Compute m' = c'**d mod n (normal RSA decryption)m1 = pow(cp, self._dp, self._p)m2 = pow(cp, self._dq, self._q)h = ((m2 - m1) * self._u) % self._qmp = h * self._p + m1# Step 4: Compute m = m**(r-1) mod nresult = (r.inverse(self._n) * mp) % self._n# Verify no faults occurredif ciphertext != pow(result, self._e, self._n):raise ValueError("Fault detected in RSA decryption")return result5.2. Signature and Verification Primitives
私鑰簽名(加密),公鑰驗(yàn)證(解密)。
其實(shí)和5.1加解密是一樣的。
5.2.1. RSASP1
RSA Signature Primitive, version 1
# def RSASP1 (K, m):# K one of the 2 forms of private key# m message representative, an integer between 0 and n - 1 def RSASP1((n,d), m)return s = (m**d) % ndef RSASP1((p, q, dP, dQ, qInv, r_i, d_i, t_i), m):s_1 = m**dP % ps_2 = m**dQ % qif( u > 2):s_i = m**(d_i) % r_i # i = 3, ..., uh = (s_1 - s_2) * qInv % ps = s_2 + q * hif ( u > 2 ):R = r_1for i in range(3, u+1):R = R * r_(i-1)h = (s_i - s) * t_i mod r_is = s + R * hreturn s5.2.2. RSAVP1
RSA Verification Primitive, version 1
def RSAVP1 ((n, e), s):# an integer between 0 and n - 1return m = s**e % n6. Overview of Schemes
這一部分僅涉及RSA對(duì)數(shù)據(jù)的處理,實(shí)際應(yīng)用中還要有密鑰管理,如密鑰獲取和驗(yàn)證。
Two types of scheme(方案) :
- encryption schemes
- RSAES-OAEP (Section 7.1)
- RSAES-PKCS1-v1_5 (Section 7.2)
- signature schemes
- RSASSA-PSS (Section 8.1)
- RSASSA-PKCS1-v1_5 (Section 8.2)
一對(duì)密鑰僅能用于一種應(yīng)用方案。
加解密示例
# from Crypto.Util.number import inverse def inverse(u, v):"""The inverse of :data:`u` *mod* :data:`v`."""u3, v3 = u, vu1, v1 = 1, 0while v3 > 0:q = u3 // v3u1, v1 = v1, u1 - v1*qu3, v3 = v3, u3 - v3*qwhile u1<0:u1 = u1 + vreturn u1def gcd(a:int, b:int):if ( b > a):a,b = b, awhile b:a,b = b, a % breturn a;def lcm(a:int, b:int):# 最小公倍數(shù)=兩數(shù)相乘/兩數(shù)的最大公約數(shù)a1 = ab1 = bwhile b1:a1,b1 = b1, a1 % b1 #a1為最大公約數(shù)return (a * b // a1)p = 17 q = 19 n = p * q # 323 L = lcm(p-1, q-1) # 144 e = 5 # gcd(e, L) = 1 d = inverse(e,L) # 29 * 5 mod 323 == 1# RSAEP Condition: 0 < m < n m = 123 cipher = (m**e)%n # 255 decrypt = (cipher**d)%n # 123OpenSSL接口
接口
OpenSSL 3.0以前:
https://www.openssl.org/docs/man3.0/man3/RSA_new.html https://www.openssl.org/docs/man3.0/man3/RSA_generate_key.htmlOpenSSL 3.0以后:
- https://www.openssl.org/docs/man3.0/man7/EVP_PKEY-RSA.html
- https://www.openssl.org/docs/man3.0/man3/EVP_PKEY_generate.html
- https://www.openssl.org/docs/man3.0/man3/PEM_write_PrivateKey.html
Demo:
- \demos\pkey\EVP_PKEY_RSA_keygen.c
命令
openssl genrsa --help openssl rsautl -help openssl rsa -help openssl genrsa -out prikey.pem 1024openssl rsa -in prikey.pem -RSAPublicKey_out -out pubkey.pem # -----BEGIN RSA PUBLIC KEY----- openssl rsa -in prikey.pem -pubout -out pubkey.pem # -----BEGIN PUBLIC KEY----- # 用-pubout openssl rsautl -encrypt -in data.txt -inkey pubkey.pem -pubin -out data_enc.txt openssl rsautl -decrypt -in data_enc.txt -inkey prikey.pem -out data_dec.txt實(shí)現(xiàn)
https://github.com/C0deStarr/CryptoImp/pubkey/rsa
參考資料
RFC 8017: PKCS #1: RSA Cryptography Specifications Version 2.2
NIST.SP.800-56Br2-Recommendation for Pair-Wise Key Establishment Using Integer Factorization Cryptography (nist.gov)
FIPS 186-4, Digital Signature Standard (DSS) | CSRC (nist.gov)
總結(jié)
- 上一篇: python数据收集整理教案_数据收集整
- 下一篇: JS与Android的交互