def optimal_pss_params(self, key: keys.PublicKeyInfo, digest_algo: str) -> algos.RSASSAPSSParams: from cryptography.hazmat.primitives.asymmetric import rsa, padding from cryptography.hazmat.primitives import serialization, hashes digest_algo = digest_algo.lower() if key.algorithm == 'rsassa_pss': # again, pretend that we're working with a normal RSA key key = key.copy() key['algorithm'] = {'algorithm': 'rsa'} loaded_key: rsa.RSAPublicKey \ = serialization.load_der_public_key(key.dump()) md = getattr(hashes, digest_algo.upper()) # the PSS salt calculation function is not in the .pyi file, apparently. # noinspection PyUnresolvedReferences optimal_salt_len = padding.calculate_max_pss_salt_length( loaded_key, md()) return algos.RSASSAPSSParams({ 'hash_algorithm': algos.DigestAlgorithm({'algorithm': digest_algo}), 'mask_gen_algorithm': algos.MaskGenAlgorithm({ 'algorithm': 'mgf1', 'parameters': algos.DigestAlgorithm({'algorithm': digest_algo}), }), 'salt_length': optimal_salt_len })
def decode_ec_public_key(der, encode_ec_point=True): """ Decode a DER-encoded EC public key as stored by OpenSSL into a dictionary of attributes able to be passed to :meth:`pkcs11.Session.create_object`. .. note:: **encode_ec_point** For use as an attribute `EC_POINT` should be DER-encoded (True). For key derivation implementations can vary. Since v2.30 the specification says implementations MUST accept a raw `EC_POINT` for ECDH (False), however not all implementations follow this yet. :param bytes der: DER-encoded key :param encode_ec_point: See text. :rtype: dict(Attribute,*) """ asn1 = PublicKeyInfo.load(der) assert asn1.algorithm == 'ec', \ "Wrong algorithm, not an EC key!" ecpoint = bytes(asn1['public_key']) if encode_ec_point: ecpoint = OctetString(ecpoint).dump() return { Attribute.KEY_TYPE: KeyType.EC, Attribute.CLASS: ObjectClass.PUBLIC_KEY, Attribute.EC_PARAMS: asn1['algorithm']['parameters'].dump(), Attribute.EC_POINT: ecpoint, }
def generate_csr(self, private_key, subject_name, extensions=None): common_name = subject_name.get_attributes_for_oid( NameOID.COMMON_NAME)[0].value info = CertificationRequestInfo({ 'version': 0, 'subject': Name.build({ 'country_name': 'US', 'state_or_province_name': 'North Carolina', 'organization_name': 'Hyperledger', 'organizational_unit_name': 'Fabric', 'common_name': common_name }), 'subject_pk_info': PublicKeyInfo.load(encode_ec_public_key(private_key.public_key)), 'attributes': CRIAttributes([]) }) hash = hashlib.sha256(info.dump()).digest() signature = private_key.private_key.sign(hash, mechanism=Mechanism.ECDSA) csr = CertificationRequest({ 'certification_request_info': info, 'signature_algorithm': { 'algorithm': 'sha256_ecdsa', 'parameters': None }, 'signature': encode_ecdsa_signature(signature) }) der = csr.dump() result = x509.load_der_x509_csr(der, default_backend()) return result
def create_spkac(private_key, challenge=''): public_key = private_key.public_key() public_der = public_key.public_bytes( encoding=serialization.Encoding.DER, format=serialization.PublicFormat.SubjectPublicKeyInfo, ) pkac = PKAC() pkac['spki'] = PublicKeyInfo.wrap(public_der, 'rsa') pkac['spki']['public_key'] = OrderedDict([ ('modulus', public_key.public_numbers().n), ('public_exponent', public_key.public_numbers().e), ]) pkac['challenge'] = '' spkac = SPKAC() spkac['publicKeyAndChallenge'] = pkac spkac['signatureAlgorithm'] = OrderedDict([ ('algorithm', SignatureAlgorithmOID.RSA_WITH_MD5.dotted_string), ('parameters', Null()), ]) spkac['signature'] = private_key.sign( spkac['publicKeyAndChallenge'].dump(), padding.PKCS1v15(), hashes.MD5(), ) return base64.b64encode(spkac.dump())
def _key_identifier_from_public_key(public_key): if isinstance(public_key, RSAPublicKey): data = public_key.public_bytes( serialization.Encoding.DER, serialization.PublicFormat.PKCS1, ) elif isinstance(public_key, EllipticCurvePublicKey): data = public_key.public_numbers().encode_point() else: # This is a very slow way to do this. serialized = public_key.public_bytes( serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo) data = six.binary_type(PublicKeyInfo.load(serialized)['public_key']) return hashlib.sha1(data).digest()
def encode_ec_public_key(key): """ Encode a DER-encoded EC public key as stored by OpenSSL. :param PublicKey key: EC public key :rtype: bytes """ ecparams = ECDomainParameters.load(key[Attribute.EC_PARAMS]) ecpoint = bytes(OctetString.load(key[Attribute.EC_POINT])) return PublicKeyInfo({ 'algorithm': { 'algorithm': 'ec', 'parameters': ecparams, }, 'public_key': ecpoint, }).dump()
def _key_identifier_from_public_key(public_key): if isinstance(public_key, RSAPublicKey): data = public_key.public_bytes( serialization.Encoding.DER, serialization.PublicFormat.PKCS1, ) elif isinstance(public_key, EllipticCurvePublicKey): data = public_key.public_numbers().encode_point() else: # This is a very slow way to do this. serialized = public_key.public_bytes( serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo ) data = six.binary_type(PublicKeyInfo.load(serialized)['public_key']) return hashlib.sha1(data).digest()
def exchange(self): key = ec.generate_private_key( curve=self.name_curved.curve, backend=default_backend(), ) args = (Encoding.DER, PublicFormat.SubjectPublicKeyInfo) der = key.public_key().public_bytes(*args) info = PublicKeyInfo.load(der) header = der[:len(der) - len(self.public_key)] server_public_key = load_der_public_key(header + self.public_key, default_backend()) shared_key = key.exchange(ec.ECDH(), server_public_key) return shared_key, len(info['public_key'].native).to_bytes( 1, 'big'), info['public_key'].native
def _key_identifier_from_public_key(public_key): if isinstance(public_key, RSAPublicKey): data = public_key.public_bytes( serialization.Encoding.DER, serialization.PublicFormat.PKCS1, ) elif isinstance(public_key, EllipticCurvePublicKey): data = public_key.public_bytes( serialization.Encoding.X962, serialization.PublicFormat.UncompressedPoint) else: # This is a very slow way to do this. serialized = public_key.public_bytes( serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo) data = bytes(PublicKeyInfo.load(serialized)['public_key']) return hashlib.sha1(data).digest()
def _key_identifier_from_public_key(public_key): if isinstance(public_key, RSAPublicKey): data = public_key.public_bytes( serialization.Encoding.DER, serialization.PublicFormat.PKCS1, ) elif isinstance(public_key, EllipticCurvePublicKey): data = public_key.public_bytes( serialization.Encoding.X962, serialization.PublicFormat.UncompressedPoint ) else: # This is a very slow way to do this. serialized = public_key.public_bytes( serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo ) data = bytes(PublicKeyInfo.load(serialized)['public_key']) return hashlib.sha1(data).digest()
def public_key_bytes(self) -> bytes: if len(self.message.public_key) == 33: return self.message.public_key public_key_info = PublicKeyInfo.load(self.message.public_key) public_key = cPublicKey(public_key_info.native['public_key']) return public_key.format(compressed=True)