日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

PKCS1_RSA

發(fā)布時間:2024/3/13 编程问答 42 豆豆
生活随笔 收集整理的這篇文章主要介紹了 PKCS1_RSA 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

文章目錄

  • 3. Key Types
    • 公鑰質數E
    • 生成隨機大質數p和q
      • 判斷素數
    • 求最小公倍數L
    • 求私鑰質數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接口
    • 接口
    • 命令
  • 實現(xiàn)
  • 參考資料

RSA的RFC文檔已經更新了很多次,截至本文(2023.1),最新的文檔是 RFC 8017: PKCS #1: RSA Cryptography Specifications Version 2.2。在頁面開頭搜索關鍵詞Obsolete可以鏈接到歷史文檔。應用較廣的版本是 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,涉及多個標準,其中PKCS #1為RSA的標準,可以在RFC官網搜索PKCS查閱。

簡介:

  • 命名取自三位發(fā)明者的姓氏字母Ron Rivest、Adi Shamir、Leonard Adleman;
  • 官網:https://rsa.com/
  • 1983年申請專利,現(xiàn)已過期,所以可以商用;
  • 公鑰密碼基于數學困難問題保證機密性,RSA的基礎是,大整數質因數分解十分困難;
  • RSA的實現(xiàn)通常會用到Base64,主要是為了防止產生亂碼;
  • RSA的密鑰長度、密文和簽名長度與模量n一致,比如2048 bits(256 bytes),參考FIPS記為nlen,RSA的安全強度與模量n的位數相關聯(lián);
    • 2017年根據ECRYPT報告,建議長度不少于2048 bits;
    • FIPS 186-4簽名標準中為1024, 2048 和3072 bits;
  • 簽名和解密(基于私鑰)比驗簽和加密(基于公鑰)慢;

文章與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中還有第二種表示法,參數很多,感興趣的可查看原文檔。

密鑰生成步驟參考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

術語:

  • LCM, Least Common Multiple, 最小公倍數。
  • GCM, Greatest Common , 最大公約數。

公鑰質數E

根據FIPS 186-4 B.3.1 1(b),E使用滿足以下條件的默認值即可:

2^16 < e < 2^256 65537 == 2^16 + 1 # default

若E采用隨機值,則性能不可控。

生成隨機大質數p和q

需要使用偽隨機數生成器生成這兩個大質數,

  • (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。

生成方法有兩種:

  • Provable primes (see Appendix B.3.2)
  • Probable primes (see Appendix B.3.3).
  • 判斷素數

    方法有很多,FIPS 186-4 C.3 PROBABILISTIC PRIMALITY TESTS提供了以下方法:

    • Miller-Rabin Probabilistic Primality Test
    • Enhanced Miller-Rabin Probabilistic Primality Test
    • (General) Lucas Probabilistic Primality Test

    其它還有費馬素性檢測(Fermat Primality Test)等。

    參考代碼:\Crypto\Math\Primality.py

    求最小公倍數L

    L = LCM(p-1, q-1)

    GCD(E, L) == 1,保證一定存在私鑰中的D;

    求私鑰質數D

    2nlen/2 < D < L,若不滿足需要重新生成p和q。

    E x D mod L == 1,保證可以解密還原明文。

    即:D = E-1mod L

    等價于: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 result

    5.2. Signature and Verification Primitives

    私鑰簽名(加密),公鑰驗證(解密)。

    其實和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 s

    5.2.2. RSAVP1

    RSA Verification Primitive, version 1

    def RSAVP1 ((n, e), s):# an integer between 0 and n - 1return m = s**e % n

    6. Overview of Schemes

    這一部分僅涉及RSA對數據的處理,實際應用中還要有密鑰管理,如密鑰獲取和驗證。

    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)

    一對密鑰僅能用于一種應用方案。

    加解密示例

    # 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):# 最小公倍數=兩數相乘/兩數的最大公約數a1 = ab1 = bwhile b1:a1,b1 = b1, a1 % b1 #a1為最大公約數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 # 123

    OpenSSL接口

    接口

    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.html

    OpenSSL 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

    實現(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)

    總結

    以上是生活随笔為你收集整理的PKCS1_RSA的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。