1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
|
"""
Key handling utilities for RSA keys (PKCS#1).
"""
from asn1crypto.keys import RSAPrivateKey, RSAPublicKey
from . import biginteger
from ..constants import Attribute, ObjectClass, MechanismFlag
from ..mechanisms import KeyType
from ..defaults import DEFAULT_KEY_CAPABILITIES
def decode_rsa_private_key(der, capabilities=None):
"""
Decode a RFC2437 (PKCS#1) DER-encoded RSA private key into a dictionary of
attributes able to be passed to :meth:`pkcs11.Session.create_object`.
:param bytes der: DER-encoded key
:param MechanismFlag capabilities: Optional key capabilities
:rtype: dict(Attribute,*)
"""
if capabilities is None:
capabilities = DEFAULT_KEY_CAPABILITIES[KeyType.RSA]
key = RSAPrivateKey.load(der)
return {
Attribute.CLASS: ObjectClass.PRIVATE_KEY,
Attribute.KEY_TYPE: KeyType.RSA,
Attribute.MODULUS: biginteger(key['modulus']),
Attribute.PUBLIC_EXPONENT: biginteger(key['public_exponent']),
Attribute.PRIVATE_EXPONENT: biginteger(key['private_exponent']),
Attribute.PRIME_1: biginteger(key['prime1']),
Attribute.PRIME_2: biginteger(key['prime2']),
Attribute.EXPONENT_1: biginteger(key['exponent1']),
Attribute.EXPONENT_2: biginteger(key['exponent2']),
Attribute.COEFFICIENT: biginteger(key['coefficient']),
Attribute.DECRYPT: MechanismFlag.DECRYPT in capabilities,
Attribute.SIGN: MechanismFlag.SIGN in capabilities,
Attribute.UNWRAP: MechanismFlag.UNWRAP in capabilities,
}
def decode_rsa_public_key(der, capabilities=None):
"""
Decode a RFC2437 (PKCS#1) DER-encoded RSA public key into a dictionary of
attributes able to be passed to :meth:`pkcs11.Session.create_object`.
:param bytes der: DER-encoded key
:param MechanismFlag capabilities: Optional key capabilities
:rtype: dict(Attribute,*)
"""
if capabilities is None:
capabilities = DEFAULT_KEY_CAPABILITIES[KeyType.RSA]
key = RSAPublicKey.load(der)
return {
Attribute.CLASS: ObjectClass.PUBLIC_KEY,
Attribute.KEY_TYPE: KeyType.RSA,
Attribute.MODULUS: biginteger(key['modulus']),
Attribute.PUBLIC_EXPONENT: biginteger(key['public_exponent']),
Attribute.ENCRYPT: MechanismFlag.ENCRYPT in capabilities,
Attribute.VERIFY: MechanismFlag.VERIFY in capabilities,
Attribute.WRAP: MechanismFlag.WRAP in capabilities,
}
def encode_rsa_public_key(key):
"""
Encode an RSA public key into PKCS#1 DER-encoded format.
:param PublicKey key: RSA public key
:rtype: bytes
"""
return RSAPublicKey({
'modulus': int.from_bytes(key[Attribute.MODULUS], byteorder='big'),
'public_exponent': int.from_bytes(key[Attribute.PUBLIC_EXPONENT],
byteorder='big'),
}).dump()
|