加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
RSA.py 26.61 KB
一键复制 编辑 原始数据 按行查看 历史
Dawn 提交于 2020-07-20 16:57 . first commit
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759
__all__ = ['generate', 'construct', 'import_key',
'RsaKey', 'oid']
import binascii
import struct
from Crypto import Random
from Crypto.Util.py3compat import tobytes, bord, tostr
from Crypto.Util.asn1 import DerSequence
from Crypto.Math.Numbers import Integer
from Crypto.Math.Primality import (test_probable_prime,
generate_probable_prime, COMPOSITE)
from Crypto.PublicKey import (_expand_subject_public_key_info,
_create_subject_public_key_info,
_extract_subject_public_key_info)
class RsaKey(object):
# 初始化属性
def __init__(self, **kwargs):
input_set = set(kwargs.keys())
public_set = set(('n', 'e'))
private_set = public_set | set(('p', 'q', 'd', 'u'))
if input_set not in (private_set, public_set):
raise ValueError("Some RSA components are missing")
# 将属性改为下划线形式,对应值保持不变
for component, value in kwargs.items():
setattr(self, "_" + component, value)
# d = (e⁻¹) mod (p-1)(q-1)
# 中国剩余定理
# d = (e⁻¹) mod (p-1)
# d = (e⁻¹) mod (q-1)
if input_set == private_set:
self._dp = self._d % (self._p - 1) # = (e⁻¹) mod (p-1)
self._dq = self._d % (self._q - 1) # = (e⁻¹) mod (q-1)
@property
def n(self):
return int(self._n)
@property
def e(self):
return int(self._e)
@property
def d(self):
if not self.has_private():
raise AttributeError("No private exponent available for public keys")
return int(self._d)
@property
def p(self):
if not self.has_private():
raise AttributeError("No CRT component 'p' available for public keys")
return int(self._p)
@property
def q(self):
if not self.has_private():
raise AttributeError("No CRT component 'q' available for public keys")
return int(self._q)
@property
def u(self):
if not self.has_private():
raise AttributeError("No CRT component 'u' available for public keys")
return int(self._u)
def size_in_bits(self):
"""
RSA模数的大小(以位为单位)
返回 n 的值的位数(右移计数)
"""
return self._n.size_in_bits()
def size_in_bytes(self):
"""
可以容纳RSA模数的最小字节数
返回 n 的字节数
"""
return (self._n.size_in_bits() - 1) // 8 + 1
def _encrypt(self, plaintext):
if not 0 <= plaintext < self._n:
raise ValueError("Plaintext too large")
# 返回 m^e (mod n)
return int(pow(Integer(plaintext), self._e, self._n))
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")
# 盲RSA解密(以防止定时攻击):
# Step 1: 产生随机秘密致盲因子r,
# 如 0 < r < n-1
r = Integer.random_range(min_inclusive=1, max_exclusive=self._n)
# Step 2: 计算 c' = c * r^e (mod n)
cp = Integer(ciphertext) * pow(r, self._e, self._n) % self._n
# Step 3: 计算 m' = c'^d (mod n) (normal RSA decryption)
# CRT 中国剩余定理
m1 = pow(cp, self._dp, self._p)
m2 = pow(cp, self._dq, self._q)
# MRC 混合基数转换法 最佳算法 SRC普通解法 https://wenku.baidu.com/view/ce1551d280eb6294dd886c0d.html
h = ((m2 - m1) * self._u) % self._q
mp = h * self._p + m1
# Step 4: 计算 m = m'**(r-1) mod n 没理解是啥意思
result = (r.inverse(self._n) * mp) % self._n
if ciphertext != pow(result, self._e, self._n):
raise ValueError("Fault detected in RSA decryption")
return result
def has_private(self):
"""Whether this is an RSA private key"""
return hasattr(self, "_d")
def can_encrypt(self): # legacy
return True
def can_sign(self): # legacy
return True
def publickey(self):
"""A matching RSA public key.
Returns:
a new :class:`RsaKey` object
"""
return RsaKey(n=self._n, e=self._e)
def __eq__(self, other):
if self.has_private() != other.has_private():
return False
if self.n != other.n or self.e != other.e:
return False
if not self.has_private():
return True
return (self.d == other.d)
def __ne__(self, other):
return not (self == other)
def __getstate__(self):
# 无法选择RSA密钥
from pickle import PicklingError
raise PicklingError
def __repr__(self):
if self.has_private():
extra = ", d=%d, p=%d, q=%d, u=%d" % (int(self._d), int(self._p),
int(self._q), int(self._u))
else:
extra = ""
return "RsaKey(n=%d, e=%d%s)" % (int(self._n), int(self._e), extra)
def __str__(self):
if self.has_private():
key_type = "Private"
else:
key_type = "Public"
return "%s RSA key at 0x%X" % (key_type, id(self))
def export_key(self, format='PEM', passphrase=None, pkcs=1,
protection=None, randfunc=None):
"""导出 RSA key.
Args:
format (string):
封装密钥的格式:
- *'PEM'*. 默认文本编码, done according to `RFC1421`_/`RFC1423`_.
- *'DER'*. 二进制编码.
- *'OpenSSH'*. 文本编码,根据OpenSSH规范进行。
只适用于公钥(私钥不行).
passphrase (string):
(*只适用于私钥*) 用于保护输出的密码.
pkcs (integer):
(*只适用于私钥*) 用于序列化密钥的ASN.1结构。
Note that even in case of PEM
encoding, there is an inner ASN.1 DER structure.
With ``pkcs=1`` (*默认*), the private key is encoded in a
simple `PKCS#1`_ structure (``RSAPrivateKey``).
With ``pkcs=8``, the private key is encoded in a `PKCS#8`_ structure
(``PrivateKeyInfo``).
.. note::
This parameter is ignored for a public key.公钥忽略此参数
For DER and PEM, an ASN.1 DER ``SubjectPublicKeyInfo``
structure is always used.
protection (string):
(*只适用于私钥*)
The encryption scheme to use for protecting the private key.
If ``None`` (default), the behavior depends on :attr:`format`:取决于format里的形式
- For *'DER'*, the *PBKDF2 With HMAC-SHA1 And DES-EDE3-CBC* 二进制编码
scheme is used. The following operations are performed:
1. A 16 byte Triple DES key is derived from the passphrase
using :func:`Crypto.Protocol.KDF.PBKDF2` with 8 bytes salt,
and 1 000 iterations of :mod:`Crypto.Hash.HMAC`.
2. The private key is encrypted using CBC.
3. The encrypted key is encoded according to PKCS#8.
- For *'PEM'*, the obsolete PEM encryption scheme is used.
It is based on MD5 for key derivation, and Triple DES for encryption.
Specifying a value for :attr:`protection` is only meaningful for PKCS#8
(that is, ``pkcs=8``) and only if a pass phrase is present too.
只有pkcs=8时,protection才是有意义的
The supported schemes for PKCS#8 are listed in the
:mod:`Crypto.IO.PKCS8` module (see :attr:`wrap_algo` parameter).
randfunc (callable):
A function that provides random bytes. Only used for PEM encoding.
The default is :func:`Crypto.Random.get_random_bytes`.
Returns:
byte string: the encoded key
Raises:
ValueError:when the format is unknown or when you try to encrypt a private
key with *DER* format and PKCS#1.
.. warning::
If you don't provide a pass phrase, the private key will be
exported in the clear!
.. _RFC1421: http://www.ietf.org/rfc/rfc1421.txt
.. _RFC1423: http://www.ietf.org/rfc/rfc1423.txt
.. _`PKCS#1`: http://www.ietf.org/rfc/rfc3447.txt
.. _`PKCS#8`: http://www.ietf.org/rfc/rfc5208.txt
"""
if passphrase is not None:
passphrase = tobytes(passphrase)
if randfunc is None:
randfunc = Random.get_random_bytes
if format == 'OpenSSH':
e_bytes, n_bytes = [x.to_bytes() for x in (self._e, self._n)]
# 如果 e 和 n 的字节数组最高位不是0,那么就在字节数组前加上 \x00
if bord(e_bytes[0]) & 0x80:
e_bytes = b'\x00' + e_bytes
if bord(n_bytes[0]) & 0x80:
n_bytes = b'\x00' + n_bytes
keyparts = [b'ssh-rsa', e_bytes, n_bytes]
# 将元素的长度转化为字节并附在元素前边,最后连接成string
keystring = b''.join([struct.pack(">I", len(kp)) + kp for kp in keyparts])
return b'ssh-rsa ' + binascii.b2a_base64(keystring)[:-1]
# DER format is always used, even in case of PEM, which simply
# encodes it into BASE64.
# 即使使用PEM,也始终使用DER格式,只需将其编码为BASE64
# 私钥
if self.has_private():
# 转化成二进制的私钥
binary_key = DerSequence([0,
self.n,
self.e,
self.d,
self.p,
self.q,
self.d % (self.p-1),
self.d % (self.q-1),
Integer(self.q).inverse(self.p)
]).encode()
if pkcs == 1:
key_type = 'RSA PRIVATE KEY'
# der是二进制编码文件,passphrase保护输出密码,pkcs=1是私钥序列化
if format == 'DER' and passphrase:
raise ValueError("PKCS#1 private key cannot be encrypted")
else: # PKCS#8
from Crypto.IO import PKCS8
if format == 'PEM' and protection is None:
key_type = 'PRIVATE KEY'
binary_key = PKCS8.wrap(binary_key, oid, None)
else:
key_type = 'ENCRYPTED PRIVATE KEY'
if not protection:
protection = 'PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC'
binary_key = PKCS8.wrap(binary_key, oid,
passphrase, protection)
passphrase = None
# 公钥
else:
key_type = "PUBLIC KEY"
binary_key = _create_subject_public_key_info(oid,
DerSequence([self.n,
self.e])
)
if format == 'DER':
return binary_key
if format == 'PEM':
from Crypto.IO import PEM
pem_str = PEM.encode(binary_key, key_type, passphrase, randfunc)
return tobytes(pem_str)
raise ValueError("Unknown key format '%s'. Cannot export the RSA key." % format)
# Backward compatibility
exportKey = export_key
# Methods defined in PyCrypto that we don't support anymore
def sign(self, M, K):
raise NotImplementedError("Use module Crypto.Signature.pkcs1_15 instead")
def verify(self, M, signature):
raise NotImplementedError("Use module Crypto.Signature.pkcs1_15 instead")
def encrypt(self, plaintext, K):
raise NotImplementedError("Use module Crypto.Cipher.PKCS1_OAEP instead")
def decrypt(self, ciphertext):
raise NotImplementedError("Use module Crypto.Cipher.PKCS1_OAEP instead")
def blind(self, M, B):
raise NotImplementedError
def unblind(self, M, B):
raise NotImplementedError
def size(self):
raise NotImplementedError
def generate(bits, randfunc=None, e=65537):
"""Create a new RSA key pair.
该算法在其B.3.1和B.3.3部分中严格遵循NIST FIPS 186-4。
模量是两个非强可能质数的乘积。
每个素数通过适当数量的带有随机基数的Miller-Rabin检验和单个Lucas检验。
Args:
bits (integer):
密钥长度或RSA模数的大小(以位为单位)。
它必须至少为1024,但建议为2048。
FIPS标准仅定义1024、2048和3072。
randfunc (callable):
Function that returns random bytes.
The default is :func:`Crypto.Random.get_random_bytes`.
e (integer):
公开RSA指数。
它必须是一个奇数正整数。
它通常是一个很小的数字,二进制表示形式很少。 2 3 65537
FIPS标准要求公用指数至少为65537(默认值)。(0x10001,5bits)
该值是除了1、3、5、17、257之外的最小素数.
https://blog.csdn.net/luoluo_onion/article/details/78354799
Returns: an RSA key object (:class:`RsaKey`, with private key).
.. _FIPS 186-4: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
"""
if bits < 1024:
raise ValueError("RSA modulus length must be >= 1024")
if e % 2 == 0 or e < 3:
raise ValueError("RSA public exponent must be a positive, odd integer larger than 2.")
if randfunc is None:
randfunc = Random.get_random_bytes
d = n = Integer(1)
e = Integer(e)
# n的位数不为1024 2048 并且d < 2048/2*10 = 1024*10
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. 2^2047 < n <2^2048
size_q = bits // 2
size_p = bits - size_q
# 分别定义最小 p 和 q
min_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) == 1 # (e, p-1)=1
p = generate_probable_prime(exact_bits=size_p,
randfunc=randfunc,
prime_filter=filter_p)
# p和q的差值
min_distance = Integer(1) << (bits // 2 - 100)
def filter_q(candidate):
return (candidate > min_q and
(candidate - 1).gcd(e) == 1 and # (e, q-1)=1
abs(candidate - p) > min_distance) # |q - p| > 最小距离
q = generate_probable_prime(exact_bits=size_q,
randfunc=randfunc,
prime_filter=filter_q)
n = p * q
lcm = (p - 1).lcm(q - 1) # 计算p-1 和 q-1的最小公倍数
d = e.inverse(lcm) # 计算私钥
if p > q: # 保证 p < q
p, q = q, p
u = p.inverse(q) # p对模数q的逆
return RsaKey(n=n, e=e, d=d, p=p, q=q, u=u)
def construct(rsa_components, consistency_check=True):
r"""从RSA组件的元组构造RSA密钥。
模数** n **必须是两个素数的乘积。
公共指数** e **必须为奇数且大于1
In case of a private key, the following equations must apply:
.. math::
\begin{align}
p*q &= n \\
e*d &\equiv 1 ( \text{mod lcm} [(p-1)(q-1)]) \\
p*u &\equiv 1 ( \text{mod } q)
\end{align}
Args:
rsa_components (tuple):
A tuple of integers, with at least 2 and no
more than 6 items. The items come in the following order:
1. RSA modulus *n*.
2. Public exponent *e*.
3. Private exponent *d*.
Only required if the key is private.
4. First factor of *n* (*p*).
Optional, but the other factor *q* must also be present.
5. Second factor of *n* (*q*). Optional.
6. CRT coefficient *q*, that is :math:`p^{-1} \text{mod }q`. Optional.
consistency_check (boolean):
If ``True``, the library will verify that the provided components
fulfil the main RSA properties.
Raises:
ValueError: when the key being imported fails the most basic RSA validity checks.
Returns: An RSA key object (:class:`RsaKey`).
"""
class InputComps(object):
pass
input_comps = InputComps()
for (comp, value) in zip(('n', 'e', 'd', 'p', 'q', 'u'), rsa_components):
setattr(input_comps, comp, Integer(value)) # setattr(object, name, value) 属性不存在会创建一个新的对象属性,并对属性赋值
n = input_comps.n
e = input_comps.e
if not hasattr(input_comps, 'd'): # 公钥
key = RsaKey(n=n, e=e)
else: # 私钥
d = input_comps.d
if hasattr(input_comps, 'q'):
p = input_comps.p
q = input_comps.q
else: # https://www.40huo.cn/blog/get-pq-from-ned.html
ktot = d * e - 1
# e*d=1(mod phi(n)) , even,and can be represented as t*2^s.
# e*d-1 = k*phi(n) , e*d-1 = 2^s * t
t = ktot
while t % 2 == 0:
t //= 2
spotted = False
a = Integer(2)
while not spotted and a < 100:
k = Integer(t)
# Cycle through all values a^{t*2^i}=a^k
while k < ktot:
cand = pow(a, k, n)
# Check if a^k is a non-trivial root of unity (mod n)
if cand != 1 and cand != (n - 1) and pow(cand, 2, n) == 1:
# We have found a number such that (cand-1)(cand+1)=0 (mod n).
# Either of the terms divides n.
p = Integer(n).gcd(cand + 1)
spotted = True
break
k *= 2
# This value was not any good... let's try another!
a += 2
if not spotted:
raise ValueError("Unable to compute factors p and q from exponent d.")
# Found !
assert ((n % p) == 0)
q = n // p
if hasattr(input_comps, 'u'):
u = input_comps.u
else:
u = p.inverse(q)
# Build key object
key = RsaKey(n=n, e=e, d=d, p=p, q=q, u=u)
# Verify consistency of the key
if consistency_check:
# Modulus and public exponent must be coprime
if e <= 1 or e >= n:
raise ValueError("Invalid RSA public exponent")
if Integer(n).gcd(e) != 1:
raise ValueError("RSA public exponent is not coprime to modulus")
# For RSA, modulus must be odd
if not n & 1:
raise ValueError("RSA modulus is not odd")
if key.has_private():
# Modulus and private exponent must be coprime
if d <= 1 or d >= n:
raise ValueError("Invalid RSA private exponent")
if Integer(n).gcd(d) != 1:
raise ValueError("RSA private exponent is not coprime to modulus")
# Modulus must be product of 2 primes
if p * q != n:
raise ValueError("RSA factors do not match modulus")
if test_probable_prime(p) == COMPOSITE:
raise ValueError("RSA factor p is composite")
if test_probable_prime(q) == COMPOSITE:
raise ValueError("RSA factor q is composite")
# See Carmichael theorem
phi = (p - 1) * (q - 1)
lcm = phi // (p - 1).gcd(q - 1)
if (e * d % int(lcm)) != 1:
raise ValueError("Invalid RSA condition")
if hasattr(key, 'u'):
# CRT coefficient
if u <= 1 or u >= q:
raise ValueError("Invalid RSA component u")
if (p * u % q) != 1:
raise ValueError("Invalid RSA component u with p")
return key
def _import_pkcs1_private(encoded, *kwargs):
# RSAPrivateKey ::= SEQUENCE {
# version Version,
# modulus INTEGER, -- n
# publicExponent INTEGER, -- e
# privateExponent INTEGER, -- d
# prime1 INTEGER, -- p
# prime2 INTEGER, -- q
# exponent1 INTEGER, -- d mod (p-1)
# exponent2 INTEGER, -- d mod (q-1)
# coefficient INTEGER -- (inverse of q) mod p
# }
#
# Version ::= INTEGER
der = DerSequence().decode(encoded, nr_elements=9, only_ints_expected=True)
if der[0] != 0:
raise ValueError("No PKCS#1 encoding of an RSA private key")
return construct(der[1:6] + [Integer(der[4]).inverse(der[5])])
def _import_pkcs1_public(encoded, *kwargs):
# RSAPublicKey ::= SEQUENCE {
# modulus INTEGER, -- n
# publicExponent INTEGER -- e
# }
der = DerSequence().decode(encoded, nr_elements=2, only_ints_expected=True)
return construct(der)
def _import_subjectPublicKeyInfo(encoded, *kwargs):
algoid, encoded_key, params = _expand_subject_public_key_info(encoded)
if algoid != oid or params is not None:
raise ValueError("No RSA subjectPublicKeyInfo")
return _import_pkcs1_public(encoded_key)
def _import_x509_cert(encoded, *kwargs):
sp_info = _extract_subject_public_key_info(encoded)
return _import_subjectPublicKeyInfo(sp_info)
def _import_pkcs8(encoded, passphrase):
from Crypto.IO import PKCS8
k = PKCS8.unwrap(encoded, passphrase)
if k[0] != oid:
raise ValueError("No PKCS#8 encoded RSA key")
return _import_keyDER(k[1], passphrase)
def _import_keyDER(extern_key, passphrase):
"""Import an RSA key (public or private half), encoded in DER form."""
decodings = (_import_pkcs1_private,
_import_pkcs1_public,
_import_subjectPublicKeyInfo,
_import_x509_cert,
_import_pkcs8)
for decoding in decodings:
try:
return decoding(extern_key, passphrase)
except ValueError:
pass
raise ValueError("RSA key format is not supported")
def _import_openssh_private_rsa(data, password):
from ._openssh import (import_openssh_private_generic,
read_bytes, read_string, check_padding)
ssh_name, decrypted = import_openssh_private_generic(data, password)
if ssh_name != "ssh-rsa":
raise ValueError("This SSH key is not RSA")
n, decrypted = read_bytes(decrypted)
e, decrypted = read_bytes(decrypted)
d, decrypted = read_bytes(decrypted)
iqmp, decrypted = read_bytes(decrypted)
p, decrypted = read_bytes(decrypted)
q, decrypted = read_bytes(decrypted)
_, padded = read_string(decrypted) # Comment
check_padding(padded)
build = [Integer.from_bytes(x) for x in (n, e, d, q, p, iqmp)]
return construct(build)
def import_key(extern_key, passphrase=None):
"""Import an RSA key (public or private).
Args:
extern_key (string or byte string):
The RSA key to import.
The following formats are supported for an RSA **public key**:
- X.509 certificate (binary or PEM format)
- X.509 ``subjectPublicKeyInfo`` DER SEQUENCE (binary or PEM
encoding)
- `PKCS#1`_ ``RSAPublicKey`` DER SEQUENCE (binary or PEM encoding)
- An OpenSSH line (e.g. the content of ``~/.ssh/id_ecdsa``, ASCII)
The following formats are supported for an RSA **private key**:
- PKCS#1 ``RSAPrivateKey`` DER SEQUENCE (binary or PEM encoding)
- `PKCS#8`_ ``PrivateKeyInfo`` or ``EncryptedPrivateKeyInfo``
DER SEQUENCE (binary or PEM encoding)
- OpenSSH (text format, introduced in `OpenSSH 6.5`_)
For details about the PEM encoding, see `RFC1421`_/`RFC1423`_.
passphrase (string or byte string):
For private keys only, the pass phrase that encrypts the key.
Returns: An RSA key object (:class:`RsaKey`).
Raises:
ValueError/IndexError/TypeError:
When the given key cannot be parsed (possibly because the pass
phrase is wrong).
.. _RFC1421: http://www.ietf.org/rfc/rfc1421.txt
.. _RFC1423: http://www.ietf.org/rfc/rfc1423.txt
.. _`PKCS#1`: http://www.ietf.org/rfc/rfc3447.txt
.. _`PKCS#8`: http://www.ietf.org/rfc/rfc5208.txt
.. _`OpenSSH 6.5`: https://flak.tedunangst.com/post/new-openssh-key-format-and-bcrypt-pbkdf
"""
from Crypto.IO import PEM
# string or byte string 转化为bytes
extern_key = tobytes(extern_key)
# passphrase : 密码短语
if passphrase is not None:
passphrase = tobytes(passphrase)
if extern_key.startswith(b'-----BEGIN OPENSSH PRIVATE KEY'):
text_encoded = tostr(extern_key)
openssh_encoded, marker, enc_flag = PEM.decode(text_encoded, passphrase)
result = _import_openssh_private_rsa(openssh_encoded, passphrase)
return result
if extern_key.startswith(b'-----'):
# This is probably a PEM encoded key.
(der, marker, enc_flag) = PEM.decode(tostr(extern_key), passphrase)
if enc_flag:
passphrase = None
return _import_keyDER(der, passphrase)
if extern_key.startswith(b'ssh-rsa '):
# This is probably an OpenSSH key
keystring = binascii.a2b_base64(extern_key.split(b' ')[1])
keyparts = []
while len(keystring) > 4:
length = struct.unpack(">I", keystring[:4])[0]
keyparts.append(keystring[4:4 + length])
keystring = keystring[4 + length:]
e = Integer.from_bytes(keyparts[1])
n = Integer.from_bytes(keyparts[2])
return construct([n, e])
if len(extern_key) > 0 and bord(extern_key[0]) == 0x30:
# This is probably a DER encoded key
return _import_keyDER(extern_key, passphrase)
raise ValueError("RSA key format is not supported")
# Backward compatibility
importKey = import_key
#: `Object ID`_ for the RSA encryption algorithm. This OID often indicates
#: a generic RSA key, even when such key will be actually used for digital
#: signatures.
#:
#: .. _`Object ID`: http://www.alvestrand.no/objectid/1.2.840.113549.1.1.1.html
# RSA加密算法的对象ID。 该OID通常指示通用的RSA密钥,即使该密钥实际用于数字签名也是如此。
oid = "1.2.840.113549.1.1.1"
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化