Python cryptography.hazmat.primitives.asymmetric.padding.PSS Examples
The following are 30
code examples of cryptography.hazmat.primitives.asymmetric.padding.PSS().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
cryptography.hazmat.primitives.asymmetric.padding
, or try the search function
.
Example #1
Source File: algorithms.py From Tautulli with GNU General Public License v3.0 | 6 votes |
def verify(self, msg, key, sig): verifier = key.verifier( sig, padding.PSS( mgf=padding.MGF1(self.hash_alg()), salt_length=self.hash_alg.digest_size ), self.hash_alg() ) verifier.update(msg) try: verifier.verify() return True except InvalidSignature: return False
Example #2
Source File: crypto.py From privacyidea with GNU Affero General Public License v3.0 | 6 votes |
def sign(self, s): """ Create a signature of the string s :param s: String to sign :type s: str :return: The hexlified and versioned signature of the string :rtype: str """ if not self.private: log.info('Could not sign message {0!s}, no private key!'.format(s)) # TODO: should we throw an exception in this case? return '' signature = self.private.sign( to_bytes(s), asym_padding.PSS( mgf=asym_padding.MGF1(hashes.SHA256()), salt_length=asym_padding.PSS.MAX_LENGTH), hashes.SHA256()) res = ':'.join([self.sig_ver, hexlify_and_unicode(signature)]) return res
Example #3
Source File: rsa_crypto.py From jx-sqlite with Mozilla Public License 2.0 | 6 votes |
def verify(signed, public_key): data = base642bytes(signed.data) signature = base642bytes(signed.signature) key = RSAPublicNumbers( public_key.e, base642int(public_key.n) ).public_key(BACKEND) key.verify( signature=signature, data=data, padding=PADDING.get(signed.padding, PSS), algorithm=ALGORITHM.get(signed.algorithm, SHA256), ) return json2value(data.decode("utf8"))
Example #4
Source File: crypto.py From keylime with BSD 2-Clause "Simplified" License | 6 votes |
def rsa_verify(public_key, message, signature): """ RSA verify message """ try: public_key.verify( base64.b64decode(signature), message, padding.PSS( mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH ), hashes.SHA256() ) except exceptions.InvalidSignature: return False except Exception as e: raise e return True
Example #5
Source File: pkcs1.py From scapy with GNU General Public License v2.0 | 6 votes |
def _get_padding(padStr, mgf=padding.MGF1, h=hashes.SHA256, label=None): if padStr == "pkcs": return padding.PKCS1v15() elif padStr == "pss": # Can't find where this is written, but we have to use the digest # size instead of the automatic padding.PSS.MAX_LENGTH. return padding.PSS(mgf=mgf(h), salt_length=h.digest_size) elif padStr == "oaep": return padding.OAEP(mgf=mgf(h), algorithm=h, label=label) else: warning("Key.encrypt(): Unknown padding type (%s)", padStr) return None ##################################################################### # Asymmetric Cryptography wrappers ##################################################################### # Make sure that default values are consistent across the whole TLS module, # lest they be explicitly set to None between cert.py and pkcs1.py.
Example #6
Source File: Trust.py From Uranium with GNU Lesser General Public License v3.0 | 6 votes |
def getFileSignature(cls, filename: str, private_key: RSAPrivateKey) -> Optional[str]: """Creates the signature for the (hash of the) provided file, given a private key. :param filename: The file to be signed. :param private_key: The private key used for signing. :return: The signature if successful, 'None' otherwise. """ file_hash = cls.getFileHash(filename) if file_hash is None: return None try: file_hash_bytes = base64.b64decode(file_hash) signature_bytes = private_key.sign( file_hash_bytes, padding.PSS(mgf = padding.MGF1(cls.__hash_algorithm), salt_length = padding.PSS.MAX_LENGTH), Prehashed(cls.__hash_algorithm) ) return base64.b64encode(signature_bytes).decode("utf-8") except: # Yes, we do really want this on _every_ exception that might occur. Logger.logException("e", "Couldn't sign '{0}', no signature generated.".format(filename)) return None
Example #7
Source File: Trust.py From Uranium with GNU Lesser General Public License v3.0 | 6 votes |
def _verifyFile(self, filename: str, signature: str) -> bool: if self._public_key is None: return False file_hash = TrustBasics.getFileHash(filename) if file_hash is None: return False try: signature_bytes = base64.b64decode(signature) file_hash_bytes = base64.b64decode(file_hash) self._public_key.verify( signature_bytes, file_hash_bytes, padding.PSS(mgf = padding.MGF1(TrustBasics.getHashAlgorithm()), salt_length = padding.PSS.MAX_LENGTH), Prehashed(TrustBasics.getHashAlgorithm()) ) return True except: # Yes, we do really want this on _every_ exception that might occur. self._violation_handler("Couldn't verify '{0}' with supplied signature.".format(filename)) return False
Example #8
Source File: test_engine.py From PyKMIP with Apache License 2.0 | 6 votes |
def test_verify_signature_invalid_signing_key(self): """ Test that the right error is raised when an invalid signing key is used. """ engine = crypto.CryptographyEngine() args = ( 'invalid', b'', b'', enums.PaddingMethod.PSS ) kwargs = { 'signing_algorithm': enums.CryptographicAlgorithm.RSA, 'hashing_algorithm': enums.HashingAlgorithm.SHA_1, 'digital_signature_algorithm': None } self.assertRaisesRegex( exceptions.CryptographicFailure, "The signing key bytes could not be loaded.", engine.verify_signature, *args, **kwargs )
Example #9
Source File: test_engine.py From PyKMIP with Apache License 2.0 | 6 votes |
def test_verify_signature_pss_missing_hashing_algorithm(self): """ Test that the right error is raised when PSS padding is used and no hashing algorithm is provided. """ engine = crypto.CryptographyEngine() args = ( b'', b'', b'', enums.PaddingMethod.PSS ) kwargs = { 'signing_algorithm': enums.CryptographicAlgorithm.RSA, 'hashing_algorithm': None, 'digital_signature_algorithm': None } self.assertRaisesRegex( exceptions.InvalidField, "A hashing algorithm must be specified for PSS padding.", engine.verify_signature, *args, **kwargs )
Example #10
Source File: test_engine.py From PyKMIP with Apache License 2.0 | 5 votes |
def test_verify_signature_invalid_signature(self): """ Test that verifying an invalid signature returns the right value. """ engine = crypto.CryptographyEngine() backend = backends.default_backend() public_key_numbers = rsa.RSAPublicNumbers( int('010001', 16), int( 'ac13d9fdae7b7335b69cd98567e9647d99bf373a9e05ce3435d66465f328' 'b7f7334b792aee7efa044ebc4c7a30b21a5d7a89cdb3a30dfcd9fee9995e' '09415edc0bf9e5b4c3f74ff53fb4d29441bf1b7ed6cbdd4a47f9252269e1' '646f6c1aee0514e93f6cb9df71d06c060a2104b47b7260ac37c106861dc7' '8ca5a25faa9cb2e3', 16) ) public_key = public_key_numbers.public_key(backend) public_bytes = public_key.public_bytes( serialization.Encoding.PEM, serialization.PublicFormat.PKCS1 ) args = ( public_bytes, b'', b'', enums.PaddingMethod.PSS ) kwargs = { 'signing_algorithm': enums.CryptographicAlgorithm.RSA, 'hashing_algorithm': enums.HashingAlgorithm.SHA_1, 'digital_signature_algorithm': None } self.assertFalse( engine.verify_signature(*args, **kwargs) )
Example #11
Source File: algorithms.py From Tautulli with GNU General Public License v3.0 | 5 votes |
def sign(self, msg, key): signer = key.signer( padding.PSS( mgf=padding.MGF1(self.hash_alg()), salt_length=self.hash_alg.digest_size ), self.hash_alg() ) signer.update(msg) return signer.finalize()
Example #12
Source File: entry.py From PSPTool with GNU General Public License v3.0 | 5 votes |
def sign(self,private_key): if self.compressed: signed_data = self.get_decompressed()[:self.size_signed + self.header_len] elif self.encrypted: print_warning(f'Signing encrypted entries is not supported yet') return False else: signed_data = self[:self.size_signed + self.header_len] if private_key.key_size == 2048 : hash = hashes.SHA256() salt_length = 32 elif private_key.key_size == 4096: hash = hashes.SHA384() salt_length = 48 else: print_warning(f"Unknown key_size: {private_key.key_size}") return False try: signature = private_key.sign( signed_data, padding.PSS( mgf=padding.MGF1(hash), salt_length=salt_length ), hash ) except: print_warning("Signing exception") return False # Special fingerprint, denote that this entry was resigned with a custom key self.signature_fingerprint = hexlify(4 * b'\xDE\xAD\xBE\xEF') self.signature = signature return True
Example #13
Source File: jwsutil.py From jws with Apache License 2.0 | 5 votes |
def parse_rsa_algorithm(algorithm): """Parses Rsa's algorithm and returns tuple (hash, padding). Args: algorithm: string, RSA algorithm as defined at https://tools.ietf.org/html/rfc7518#section-3.1. Raises: UnsupportedAlgorithm: if the algorithm is not supported. Returns: (hash, padding) tuple. """ if algorithm == "RS256": return (hashes.SHA256(), padding.PKCS1v15()) elif algorithm == "RS384": return (hashes.SHA384(), padding.PKCS1v15()) elif algorithm == "RS512": return (hashes.SHA512(), padding.PKCS1v15()) elif algorithm == "PS256": return (hashes.SHA256(), padding.PSS( mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH)) elif algorithm == "PS384": return (hashes.SHA384(), padding.PSS( mgf=padding.MGF1(hashes.SHA384()), salt_length=padding.PSS.MAX_LENGTH)) elif algorithm == "PS512": return (hashes.SHA512(), padding.PSS( mgf=padding.MGF1(hashes.SHA512()), salt_length=padding.PSS.MAX_LENGTH)) else: raise exceptions.UnsupportedAlgorithm("Unknown algorithm: %s" % (algorithm))
Example #14
Source File: rsa_crypto.py From jx-sqlite with Mozilla Public License 2.0 | 5 votes |
def sign(message, private_key): data = value2json(message).encode("utf8") # SIGN DATA/STRING signature = private_key.sign(data=data, padding=PSS, algorithm=SHA256) return wrap({ "data": bytes2base64(data), "signature": bytes2base64(signature), "padding": "PSS", "algorithm=": "SHA256" })
Example #15
Source File: image_signer.py From openstacksdk with Apache License 2.0 | 5 votes |
def __init__(self, hash_method='SHA-256', padding_method='RSA-PSS'): padding_types = { 'RSA-PSS': padding.PSS( mgf=padding.MGF1(HASH_METHODS[hash_method]), salt_length=padding.PSS.MAX_LENGTH ) } # informational attributes self.hash_method = hash_method self.padding_method = padding_method # runtime objects self.private_key = None self.hash = HASH_METHODS[hash_method] self.hasher = hashes.Hash(self.hash, default_backend()) self.padding = padding_types[padding_method]
Example #16
Source File: algorithms.py From gist-alfred with MIT License | 5 votes |
def sign(self, msg, key): return key.sign( msg, padding.PSS( mgf=padding.MGF1(self.hash_alg()), salt_length=self.hash_alg.digest_size ), self.hash_alg() )
Example #17
Source File: test_engine.py From PyKMIP with Apache License 2.0 | 5 votes |
def test_verify_signature_mismatching_signing_algorithms(self): """ Test that the right error is raised when both the signing algorithm and the digital signature algorithm are provided and do not match. """ engine = crypto.CryptographyEngine() args = ( b'', b'', b'', enums.PaddingMethod.PSS ) kwargs = { 'signing_algorithm': enums.CryptographicAlgorithm.ECDSA, 'hashing_algorithm': enums.HashingAlgorithm.SHA_1, 'digital_signature_algorithm': enums.DigitalSignatureAlgorithm.SHA1_WITH_RSA_ENCRYPTION } self.assertRaisesRegex( exceptions.InvalidField, "The signing algorithm does not match the digital signature " "algorithm.", engine.verify_signature, *args, **kwargs )
Example #18
Source File: crypto.py From keylime with BSD 2-Clause "Simplified" License | 5 votes |
def rsa_sign(key, message): """ RSA sign message """ signature = key.sign( message, padding.PSS( mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH ), hashes.SHA256() ) return base64.b64encode(signature)
Example #19
Source File: espsecure.py From esptool with GNU General Public License v2.0 | 5 votes |
def verify_signature_v2(args): """ Verify a previously signed binary image, using the RSA public key """ SECTOR_SIZE = 4096 SIG_BLOCK_MAX_COUNT = 3 vk = _get_sbv2_rsa_pub_key(args.keyfile) image_content = args.datafile.read() if len(image_content) < SECTOR_SIZE or len(image_content) % SECTOR_SIZE != 0: raise esptool.FatalError("Invalid datafile. Data size should be non-zero & a multiple of 4096.") digest = digest = hashlib.sha256() digest.update(image_content[:-SECTOR_SIZE]) digest = digest.digest() for sig_blk_num in range(SIG_BLOCK_MAX_COUNT): sig_blk = validate_signature_block(image_content, sig_blk_num) if sig_blk is None: raise esptool.FatalError("Signature block %d invalid. Signature could not be verified with the provided key." % sig_blk_num) sig_data = struct.unpack("<BBxx32s384sI384sI384sI16x", sig_blk) if sig_data[2] != digest: raise esptool.FatalError("Signature block image digest does not match the actual image digest %s. Expected %s." % (digest, sig_data[2])) try: vk.verify( sig_data[-2][::-1], digest, padding.PSS( mgf=padding.MGF1(hashes.SHA256()), salt_length=32 ), utils.Prehashed(hashes.SHA256()) ) print("Signature block %d verification successful with %s." % (sig_blk_num, args.keyfile.name)) return except exceptions.InvalidSignature: print("Signature block %d is not signed by %s. Checking the next block" % (sig_blk_num, args.keyfile.name)) continue raise esptool.FatalError("Checked all blocks. Signature could not be verified with the provided key.")
Example #20
Source File: test_engine.py From PyKMIP with Apache License 2.0 | 5 votes |
def test_verify_signature_mismatching_hashing_algorithms(self): """ Test that the right error is raised when both the hashing algorithm and the digital signature algorithm are provided and do not match. """ engine = crypto.CryptographyEngine() args = ( b'', b'', b'', enums.PaddingMethod.PSS ) kwargs = { 'signing_algorithm': enums.CryptographicAlgorithm.RSA, 'hashing_algorithm': enums.HashingAlgorithm.SHA_256, 'digital_signature_algorithm': enums.DigitalSignatureAlgorithm.SHA1_WITH_RSA_ENCRYPTION } self.assertRaisesRegex( exceptions.InvalidField, "The hashing algorithm does not match the digital signature " "algorithm.", engine.verify_signature, *args, **kwargs )
Example #21
Source File: jwa.py From jwcrypto with GNU Lesser General Public License v3.0 | 5 votes |
def __init__(self): padfn = padding.PSS(padding.MGF1(hashes.SHA512()), hashes.SHA512.digest_size) super(_PS512, self).__init__(padfn, hashes.SHA512())
Example #22
Source File: jwa.py From jwcrypto with GNU Lesser General Public License v3.0 | 5 votes |
def __init__(self): padfn = padding.PSS(padding.MGF1(hashes.SHA256()), hashes.SHA256.digest_size) super(_PS256, self).__init__(padfn, hashes.SHA256())
Example #23
Source File: jwa.py From jwcrypto with GNU Lesser General Public License v3.0 | 5 votes |
def __init__(self): padfn = padding.PSS(padding.MGF1(hashes.SHA384()), hashes.SHA384.digest_size) super(_PS384, self).__init__(padfn, hashes.SHA384())
Example #24
Source File: algorithms.py From gist-alfred with MIT License | 4 votes |
def verify(self, msg, key, sig): try: key.verify( sig, msg, padding.PSS( mgf=padding.MGF1(self.hash_alg()), salt_length=self.hash_alg.digest_size ), self.hash_alg() ) return True except InvalidSignature: return False
Example #25
Source File: cert.py From arissploit with GNU General Public License v3.0 | 4 votes |
def sign(self, M, t=None, h=None, mgf=None, sLen=None): """ Sign message 'M' using 't' signature scheme where 't' can be: - None: the message 'M' is directly applied the RSASP1 signature primitive, as described in PKCS#1 v2.1, i.e. RFC 3447 Sect 5.2.1. Simply put, the message undergo a modular exponentiation using the private key. Additionnal method parameters are just ignored. - 'pkcs': the message 'M' is applied RSASSA-PKCS1-v1_5-SIGN signature scheme as described in Sect. 8.2.1 of RFC 3447. In that context, the hash function name is passed using 'h'. Possible values are "md2", "md4", "md5", "sha1", "tls", "sha224", "sha256", "sha384" and "sha512". If none is provided, sha1 is used. Other additionnal parameters are ignored. - 'pss' : the message 'M' is applied RSASSA-PSS-SIGN signature scheme as described in Sect. 8.1.1. of RFC 3447. In that context, o 'h' parameter provides the name of the hash method to use. Possible values are "md2", "md4", "md5", "sha1", "tls", "sha224", "sha256", "sha384" and "sha512". if none is provided, sha1 is used. o 'mgf' is the mask generation function. By default, mgf is derived from the provided hash function using the generic MGF1 (see pkcs_mgf1() for details). o 'sLen' is the length in octet of the salt. You can overload the default value (the octet length of the hash value for provided algorithm) by providing another one with that parameter. """ if t is None: # RSASP1 M = pkcs_os2ip(M) n = self.modulus if M > n-1: warning("Message to be signed is too long for key modulus") return None s = self._rsasp1(M) if s is None: return None return pkcs_i2osp(s, self.modulusLen/8) elif t == "pkcs": # RSASSA-PKCS1-v1_5-SIGN if h is None: h = "sha1" return self._rsassa_pkcs1_v1_5_sign(M, h) elif t == "pss": # RSASSA-PSS-SIGN return self._rsassa_pss_sign(M, h, mgf, sLen) else: warning("Key.sign(): Unknown signature type (%s) provided" % t) return None
Example #26
Source File: cert.py From arissploit with GNU General Public License v3.0 | 4 votes |
def _rsassa_pss_sign(self, M, h=None, mgf=None, sLen=None): """ Implements RSASSA-PSS-SIGN() function described in Sect. 8.1.1 of RFC 3447. Input: M: message to be signed, an octet string Output: signature, an octet string of length k, where k is the length in octets of the RSA modulus n. On error, None is returned. """ # Set default parameters if not provided if h is None: # By default, sha1 h = "sha1" if not h in _hashFuncParams: warning("Key._rsassa_pss_sign(): unknown hash function " "provided (%s)" % h) return None if mgf is None: # use mgf1 with underlying hash function mgf = lambda x,y: pkcs_mgf1(x, y, h) if sLen is None: # use Hash output length (A.2.3 of RFC 3447) hLen = _hashFuncParams[h][0] sLen = hLen # 1) EMSA-PSS encoding modBits = self.modulusLen k = modBits / 8 EM = pkcs_emsa_pss_encode(M, modBits - 1, h, mgf, sLen) if EM is None: warning("Key._rsassa_pss_sign(): unable to encode") return None # 2) RSA signature m = pkcs_os2ip(EM) # 2.a) s = self._rsasp1(m) # 2.b) S = pkcs_i2osp(s, k) # 2.c) return S # 3)
Example #27
Source File: cert.py From arissploit with GNU General Public License v3.0 | 4 votes |
def pkcs_emsa_pss_verify(M, EM, emBits, h, mgf, sLen): """ Implements EMSA-PSS-VERIFY() function described in Sect. 9.1.2 of RFC 3447 Input: M : message to be encoded, an octet string EM : encoded message, an octet string of length emLen = ceil(emBits/8) emBits: maximal bit length of the integer resulting of pkcs_os2ip(EM) h : hash function name (in 'md2', 'md4', 'md5', 'sha1', 'tls', 'sha256', 'sha384'). hLen denotes the length in octets of the hash function output. mgf : the mask generation function f : seed, maskLen -> mask sLen : intended length in octets of the salt Output: True if the verification is ok, False otherwise. """ # 1) is not done hLen = _hashFuncParams[h][0] # 2) hFunc = _hashFuncParams[h][1] mHash = hFunc(M) emLen = int(math.ceil(emBits/8.)) # 3) if emLen < hLen + sLen + 2: return False if EM[-1] != '\xbc': # 4) return False l = emLen - hLen - 1 # 5) maskedDB = EM[:l] H = EM[l:l+hLen] l = (8*emLen - emBits)/8 # 6) rem = 8*emLen - emBits - 8*l # additionnal bits andMask = l*'\xff' if rem: val = reduce(lambda x,y: x+y, map(lambda x: 1<<x, range(8-rem))) j = chr(~val & 0xff) andMask += j l += 1 if strand(maskedDB[:l], andMask) != '\x00'*l: return False dbMask = mgf(H, emLen - hLen - 1) # 7) DB = strxor(maskedDB, dbMask) # 8) l = (8*emLen - emBits)/8 # 9) rem = 8*emLen - emBits - 8*l # additionnal bits andMask = l*'\x00' if rem: j = chr(reduce(lambda x,y: x+y, map(lambda x: 1<<x, range(8-rem)))) andMask += j l += 1 DB = strand(DB[:l], andMask) + DB[l:] l = emLen - hLen - sLen - 1 # 10) if DB[:l] != '\x00'*(l-1) + '\x01': return False salt = DB[-sLen:] # 11) MPrime = '\x00'*8 + mHash + salt # 12) HPrime = hFunc(MPrime) # 13) return H == HPrime # 14)
Example #28
Source File: cert.py From arissploit with GNU General Public License v3.0 | 4 votes |
def pkcs_emsa_pss_encode(M, emBits, h, mgf, sLen): """ Implements EMSA-PSS-ENCODE() function described in Sect. 9.1.1 of RFC 3447 Input: M : message to be encoded, an octet string emBits: maximal bit length of the integer resulting of pkcs_os2ip(EM), where EM is the encoded message, output of the function. h : hash function name (in 'md2', 'md4', 'md5', 'sha1', 'tls', 'sha256', 'sha384'). hLen denotes the length in octets of the hash function output. mgf : the mask generation function f : seed, maskLen -> mask sLen : intended length in octets of the salt Output: encoded message, an octet string of length emLen = ceil(emBits/8) On error, None is returned. """ # 1) is not done hLen = _hashFuncParams[h][0] # 2) hFunc = _hashFuncParams[h][1] mHash = hFunc(M) emLen = int(math.ceil(emBits/8.)) if emLen < hLen + sLen + 2: # 3) warning("encoding error (emLen < hLen + sLen + 2)") return None salt = randstring(sLen) # 4) MPrime = '\x00'*8 + mHash + salt # 5) H = hFunc(MPrime) # 6) PS = '\x00'*(emLen - sLen - hLen - 2) # 7) DB = PS + '\x01' + salt # 8) dbMask = mgf(H, emLen - hLen - 1) # 9) maskedDB = strxor(DB, dbMask) # 10) l = (8*emLen - emBits)/8 # 11) rem = 8*emLen - emBits - 8*l # additionnal bits andMask = l*'\x00' if rem: j = chr(reduce(lambda x,y: x+y, map(lambda x: 1<<x, range(8-rem)))) andMask += j l += 1 maskedDB = strand(maskedDB[:l], andMask) + maskedDB[l:] EM = maskedDB + H + '\xbc' # 12) return EM # 13)
Example #29
Source File: entry.py From PSPTool with GNU General Public License v3.0 | 4 votes |
def verify_signature(self): # Note: This does not work if an entry was compressed AND encrypted. # However, we have not yet seen such entry. # Only verify signature if we actually have a signature if self.signature == None: return False if self.compressed: signed_data = self.get_decompressed()[:self.size_signed + self.header_len] elif self.encrypted: signed_data = self.get_decrypted()[:self.size_signed + self.header_len] else: signed_data = self.get_bytes()[:self.size_signed + self.header_len] try: pubkey_der_encoded = self.pubkey.get_der_encoded() except AttributeError: print_warning(f"Entry {self.get_readable_type()} is signed, but corresponding pubkey was not found ({self.get_readable_signed_by()})") return False crypto_pubkey = load_der_public_key(pubkey_der_encoded, backend=default_backend()) if len(self.signature) == 0x100: hash = hashes.SHA256() salt_len = 32 elif len(self.signature) == 0x200: hash = hashes.SHA384() salt_len = 48 else: print_warning("Weird signature len") return False try: crypto_pubkey.verify( self.signature.get_bytes(), signed_data, padding.PSS( mgf=padding.MGF1(hash), salt_length=salt_len ), hash ) except InvalidSignature: return False return True
Example #30
Source File: cert.py From kamene with GNU General Public License v2.0 | 4 votes |
def sign(self, M, t=None, h=None, mgf=None, sLen=None): """ Sign message 'M' using 't' signature scheme where 't' can be: - None: the message 'M' is directly applied the RSASP1 signature primitive, as described in PKCS#1 v2.1, i.e. RFC 3447 Sect 5.2.1. Simply put, the message undergo a modular exponentiation using the private key. Additionnal method parameters are just ignored. - 'pkcs': the message 'M' is applied RSASSA-PKCS1-v1_5-SIGN signature scheme as described in Sect. 8.2.1 of RFC 3447. In that context, the hash function name is passed using 'h'. Possible values are "md2", "md4", "md5", "sha1", "tls", "sha224", "sha256", "sha384" and "sha512". If none is provided, sha1 is used. Other additionnal parameters are ignored. - 'pss' : the message 'M' is applied RSASSA-PSS-SIGN signature scheme as described in Sect. 8.1.1. of RFC 3447. In that context, o 'h' parameter provides the name of the hash method to use. Possible values are "md2", "md4", "md5", "sha1", "tls", "sha224", "sha256", "sha384" and "sha512". if none is provided, sha1 is used. o 'mgf' is the mask generation function. By default, mgf is derived from the provided hash function using the generic MGF1 (see pkcs_mgf1() for details). o 'sLen' is the length in octet of the salt. You can overload the default value (the octet length of the hash value for provided algorithm) by providing another one with that parameter. """ if t is None: # RSASP1 M = pkcs_os2ip(M) n = self.modulus if M > n-1: warning("Message to be signed is too long for key modulus") return None s = self._rsasp1(M) if s is None: return None return pkcs_i2osp(s, self.modulusLen/8) elif t == "pkcs": # RSASSA-PKCS1-v1_5-SIGN if h is None: h = "sha1" return self._rsassa_pkcs1_v1_5_sign(M, h) elif t == "pss": # RSASSA-PSS-SIGN return self._rsassa_pss_sign(M, h, mgf, sLen) else: warning("Key.sign(): Unknown signature type (%s) provided" % t) return None