def verify_license(public_key_string, encoded_signature, product_code, name): base32_signature = encoded_signature.replace('8', 'O').replace('9', 'I').replace('-', '') base32_signature += '=' * (8 - (len(base32_signature) % 8)) decoded_signature = base64.b32decode(base32_signature) public_key = crypto.load_publickey(crypto.FILETYPE_PEM, public_key_string) certificate = crypto.X509() certificate.set_pubkey(public_key) try: crypto.verify(certificate, decoded_signature, make_license_source(product_code, name), 'dss1') return True except: return False
def verify_license(public_key_string, encoded_signature, product_code, name): base32_signature = encoded_signature.replace('8', 'O').replace('9', 'I').replace('-', '') base32_signature += '=' * (8 - (len(base32_signature) % 8)) decoded_signature = base64.b32decode(base32_signature) public_key = crypto.load_publickey(crypto.FILETYPE_PEM, public_key_string) certificate = crypto.X509() certificate.set_pubkey(public_key) try: crypto.verify(certificate, decoded_signature, make_license_source(product_code, name), 'sha1') # Use sha1 instead of dss1 to avoid 'ValueError("No such digest method")' return True except: return False
def verify_signature(self, crt=None, sign=None, resp_body=None): try: x509 = load_certificate(FILETYPE_PEM, crt) pub_key = x509.get_pubkey() ias_public_key = dump_publickey(FILETYPE_PEM, pub_key) public_key = load_publickey(FILETYPE_PEM, ias_public_key) x509 = X509() x509.set_pubkey(public_key) if verify(x509, base64.b64decode(sign), resp_body, 'sha256') == None: LOG.info("Signature verification Passed on Server side") return True except Exception as e: LOG.error(str(e)) raise Exception("Signature verification Failed on Server side", e)
def test_issue_certificate_without_csr(self): """ Tests issuance of a certificate """ cmd = issueCertificate.issueCertificateCmd() cmd.domain = 'apache.org,cloudstack.apache.org' cmd.ipaddress = '10.1.1.1,10.2.2.2' cmd.provider = 'root' response = self.apiclient.issueCertificate(cmd) self.assertTrue(len(response.privatekey) > 0) self.assertTrue(len(response.cacertificates) > 0) self.assertTrue(len(response.certificate) > 0) cert = x509.load_pem_x509_certificate(str(response.certificate), default_backend()) # Validate basic certificate attributes self.assertEqual(cert.signature_hash_algorithm.name, 'sha256') self.assertEqual( cert.subject.get_attributes_for_oid( x509.oid.NameOID.COMMON_NAME)[0].value, 'apache.org') # Validate alternative names altNames = cert.extensions.get_extension_for_oid( x509.oid.ExtensionOID.SUBJECT_ALTERNATIVE_NAME) for domain in cmd.domain.split(','): self.assertTrue( domain in altNames.value.get_values_for_type(x509.DNSName)) for address in cmd.ipaddress.split(','): self.assertTrue(address in map( lambda x: str(x), altNames.value.get_values_for_type(x509.IPAddress))) # Validate certificate against CA public key global PUBKEY_VERIFY if not PUBKEY_VERIFY: return caCert = x509.load_pem_x509_certificate(str(self.getCaCertificate()), default_backend()) x = X509() x.set_pubkey( load_publickey( FILETYPE_PEM, str(caCert.public_key().public_bytes( serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo)))) verify(x, cert.signature, cert.tbs_certificate_bytes, cert.signature_hash_algorithm.name)
def verify_license(public_key_string, encoded_signature, product_code, name): base32_signature = encoded_signature.replace('8', 'O').replace( '9', 'I').replace('-', '') base32_signature += '=' * (8 - (len(base32_signature) % 8)) decoded_signature = base64.b32decode(base32_signature) public_key = crypto.load_publickey(crypto.FILETYPE_PEM, public_key_string) certificate = crypto.X509() certificate.set_pubkey(public_key) try: crypto.verify(certificate, decoded_signature, make_license_source(product_code, name), 'sha1') # Use sha1 instead of dss1 to avoid 'ValueError("No such digest method")' return True except: return False
def _check_privatekey(): if not os.path.exists(self.privatekey_path): return False current_publickey = crypto.dump_publickey( crypto.FILETYPE_ASN1, crypto.load_publickey(crypto.FILETYPE_PEM, open(self.path, 'rb').read()) ) desired_publickey = crypto.dump_publickey( crypto.FILETYPE_ASN1, crypto_utils.load_privatekey(self.privatekey_path, self.privatekey_passphrase) ) return hashlib.md5(current_publickey).hexdigest() == hashlib.md5(desired_publickey).hexdigest()
def verify_data(cls, data, sign): from OpenSSL import crypto import base64 if isinstance(data, dict): data = cls.gen_url_params(data) pk = crypto.load_publickey(crypto.FILETYPE_PEM, open(WB_PUB_CERT, 'r').read()) cert = crypto.X509() cert.set_pubkey(pk) try: result = crypto.verify(cert, base64.b64decode(sign), data, 'sha1') return True except Exception as e: print e return False
def make_certs_and_key(device_public_key: bytes): priv_key = PKey() priv_key.generate_key(TYPE_RSA, 2048) req = make_req(priv_key) cert = make_cert(req, priv_key) dev_key = load_publickey(PEM, convert_PKCS1_to_PKCS8_pubkey(device_public_key)) dev_key._only_public = False dev_req = make_req(dev_key, 'Device') dev_cert = make_cert(dev_req, priv_key) return dump_certificate(PEM, cert), dump_privatekey( PEM, priv_key), dump_certificate(PEM, dev_cert)
def check_authorized(signature: str, payload: str): """Convert the PEM encoded public key to a format palatable for pyOpenSSL, then verify the signature Arguments: :param signature (str) Signature returned by sign function :param payload (str) String that is encoded """ response = requests.get('https://api.travis-ci.com/config', timeout=10.0) response.raise_for_status() public_key = response.json( )['config']['notifications']['webhook']['public_key'] pkey_public_key = load_publickey(FILETYPE_PEM, public_key) certificate = X509() certificate.set_pubkey(pkey_public_key) verify(certificate, base64.b64decode(signature), payload, str('SHA1'))
def _check_privatekey(): if not os.path.exists(self.privatekey_path): return False current_publickey = crypto.dump_publickey( crypto.FILETYPE_ASN1, crypto.load_publickey(crypto.FILETYPE_PEM, open(self.path, 'rb').read())) desired_publickey = crypto.dump_publickey( crypto.FILETYPE_ASN1, crypto_utils.load_privatekey(self.privatekey_path, self.privatekey_passphrase)) return hashlib.md5(current_publickey).hexdigest() == hashlib.md5( desired_publickey).hexdigest()
def ca_do_everything(DevicePublicKey): cakey = createKeyPair(crypto.TYPE_RSA, 2048) careq = createCertRequest(cakey, CN='Certificate Authority') # CA certificate is valid for five years. cacert = createCertificate(careq, (careq, cakey), 0, (0, 60 * 60 * 24 * 365 * 5)) pkey = crypto.load_publickey(crypto.FILETYPE_PEM, convertPKCS1toPKCS8pubKey(DevicePublicKey)) req = createCertRequest(pkey, CN='poodf') # Certificates are valid for five years. cert = createCertificate(req, (cacert, cakey), 1, (0, 60 * 60 * 24 * 365 * 5)) return (crypto.dump_certificate(crypto.FILETYPE_PEM, cacert), crypto.dump_privatekey(crypto.FILETYPE_PEM, cakey), crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
def sig_verified(message, sig): f = open(pub_key_file, 'r') pub_key_pem = f.read() f.close() pub_key = crypto.load_publickey(crypto.FILETYPE_PEM, pub_key_pem) sig = base64.b64decode(sig) pub_key_x509 = X509() pub_key_x509.set_pubkey(pub_key) try: crypto.verify(pub_key_x509, sig, message, 'sha256') logger.info("signature verified for message {}".format(message)) return True except Exception as e: logger.error("verifying signature failed for message {}: {}".format( message, e))
def generate_csr(self): req = crypto.X509Req() req.get_subject().CN = self.name req.get_subject().countryName = 'SY' req.get_subject().stateOrProvinceName = 'Damascus' req.get_subject().localityName = 'Southern Syria' req.get_subject().organizationName = 'AI inc.' req.get_subject().organizationalUnitName = 'Information Security' opensslPublicKey = crypto.load_publickey(crypto.FILETYPE_PEM, open(f'server_keys/{self.name}_public.pem').read()) opensslPrivateKey = crypto.load_privatekey(crypto.FILETYPE_PEM, open(f'server_keys/{self.name}_private.pem').read()) req.set_pubkey(opensslPublicKey) req.sign(opensslPrivateKey, "sha1") self.csr = req
def verify(cls, path_to_public_key, message, signature): """ Verifies the signature on a message. :param path_to_public_key: string, Absolute or relative path to Spectre public key :param message: string, The message to verify. :param signature: string, The signature on the message. :return: """ x509 = crypto.X509() with open(path_to_public_key, 'r') as public_key_data: public_key = crypto.load_publickey(crypto.FILETYPE_PEM, public_key_data) x509.set_pubkey(public_key) try: crypto.verify(x509, base64.b64decode(signature), message, cls.digest) return True except crypto.Error: return False
def set_pubkey(self, public_key: PublicKey): """ Modify the public key of a CSR. :param PublicKey public_key: The new public key for a CSR. :rtype: None """ openssl_req = openssl.X509Req.from_cryptography(self) key_pem = public_key.public_bytes( serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo, ) openssl_key = openssl.load_publickey(openssl.FILETYPE_PEM, key_pem) openssl_req.set_pubkey(openssl_key) self._x509_req = openssl_req.to_cryptography()._x509_req
def _check_privatekey(): if self.privatekey_content is None and not os.path.exists( self.privatekey_path): return False try: with open(self.path, 'rb') as public_key_fh: publickey_content = public_key_fh.read() self.diff_before = self.diff_after = self._get_info( publickey_content) if self.return_content: self.publickey_bytes = publickey_content if self.backend == 'cryptography': if self.format == 'OpenSSH': # Read and dump public key. Makes sure that the comment is stripped off. current_publickey = crypto_serialization.load_ssh_public_key( publickey_content, backend=default_backend()) publickey_content = current_publickey.public_bytes( crypto_serialization.Encoding.OpenSSH, crypto_serialization.PublicFormat.OpenSSH) else: current_publickey = crypto_serialization.load_pem_public_key( publickey_content, backend=default_backend()) publickey_content = current_publickey.public_bytes( crypto_serialization.Encoding.PEM, crypto_serialization.PublicFormat. SubjectPublicKeyInfo) else: publickey_content = crypto.dump_publickey( crypto.FILETYPE_PEM, crypto.load_publickey(crypto.FILETYPE_PEM, publickey_content)) except Exception as dummy: return False try: desired_publickey = self._create_publickey(module) except OpenSSLBadPassphraseError as exc: raise PublicKeyError(exc) return publickey_content == desired_publickey
def make_certs_and_key(device_public_key: bytes): """ 1. create private key 2. create certificate """ device_key = load_publickey( PEM, convert_PKCS1_to_PKCS8_pubkey(device_public_key)) device_key._only_public = False # root key root_key = PKey() root_key.generate_key(TYPE_RSA, 2048) host_req = make_req(root_key) host_cert = make_cert(host_req, root_key) device_req = make_req(device_key, 'Device') device_cert = make_cert(device_req, root_key) return dump_certificate(PEM, host_cert), dump_privatekey( PEM, root_key), dump_certificate(PEM, device_cert)
def verify_sign(self, public_key_path, data_path, base64_sign_path): logging.debug('public_key_path {}'.format(public_key_path)) logging.debug('data_path {}'.format(data_path)) with open(public_key_path, "rb") as public_key_file: key = public_key_file.read() logging.debug('key readed \n{}\n'.format(key)) pkey = crypto.load_publickey(crypto.FILETYPE_PEM, key) logging.debug('pkey loaded\n{}\n'.format(pkey)) with open(base64_sign_path, "r") as base64_sign_file: sign = base64.b64decode(base64_sign_file.read()) logging.debug('sign decoded\n{}'.format(sign)) with open(data_path) as data_file: data = data_file.read() logging.debug('data loaded\n{}'.format(data)) data_bytes = bytes(data, encoding='utf-8') certificate_x509 = OpenSSL.crypto.X509() certificate_x509.set_pubkey(pkey) OpenSSL.crypto.verify(certificate_x509, sign, data_bytes, "sha256")
def generate_csr(self): # csrfile = 'incommon.csr' req = crypto.X509Req() # Return an X509Name object representing the subject of the certificate. req.get_subject().CN = self.name req.get_subject().countryName = 'SY' req.get_subject().stateOrProvinceName = 'Damascus' req.get_subject().localityName = 'Southern Syria' # # Set the public key of the certificate to pkey. opensslPublicKey = crypto.load_publickey( crypto.FILETYPE_PEM, open(f'client_keys/{self.name}_public.pem').read()) opensslPrivateKey = crypto.load_privatekey( crypto.FILETYPE_PEM, open(f'client_keys/{self.name}_private.pem').read()) req.set_pubkey(opensslPublicKey) req.sign(opensslPrivateKey, "sha1") self.csr = req
def verifyUser(name, cert): ''' Takes in the name and certificate and checks that the name matches the signature using the public key ''' decoded = base64.b64decode(cert) with open("ca-key-public.pem", 'rb') as f: publicKey = f.read() pkey = load_publickey(FILETYPE_PEM, publicKey) x509 = X509() x509.set_pubkey(pkey) data = str.encode(name + "\n") try: verify(x509, decoded, data, 'sha256') return True except: # pylint: disable=W0702 return False
def _check_privatekey(): if not os.path.exists(self.privatekey_path): return False try: publickey_content = open(self.path, 'rb').read() if self.format == 'OpenSSH': current_publickey = crypto_serialization.load_ssh_public_key(publickey_content, backend=default_backend()) publickey_content = current_publickey.public_bytes(crypto_serialization.Encoding.PEM, crypto_serialization.PublicFormat.SubjectPublicKeyInfo) current_publickey = crypto.dump_publickey( crypto.FILETYPE_ASN1, crypto.load_publickey(crypto.FILETYPE_PEM, publickey_content) ) except (crypto.Error, ValueError): return False desired_publickey = crypto.dump_publickey( crypto.FILETYPE_ASN1, crypto_utils.load_privatekey(self.privatekey_path, self.privatekey_passphrase) ) return current_publickey == desired_publickey
def verify(path, path_sign): with open(path, "r") as f: data = f.read() key_file = open("public.pem", "r") key = key_file.read() key_file.close() if key.startswith('-----BEGIN '): pkey = crypto.load_publickey(crypto.FILETYPE_PEM, key) else: raise PermissionError data = data.encode() x509 = crypto.X509() x509.set_pubkey(pkey) with open(path_sign, "rb") as f: signature = f.read() signature = base64.b64decode(signature) try: return crypto.verify(x509, signature, data, "sha256") except: messagebox.showerror( title="Signature error", message="Your signature is not corresponding to the licence file") return 0
async def issue_cs(sid, data): req = crypto.load_certificate_request(crypto.FILETYPE_PEM, data) check_csr = f'server_keys/CA/{req.get_subject().CN}_public.pem' if os.path.exists(check_csr): crypto_public_key = crypto.load_publickey(crypto.FILETYPE_PEM, open(check_csr, 'rb').read()) if req.verify(crypto_public_key): cs = crypto.X509() ca_private_key = ca.private_key.exportKey() crypto_private_key = crypto.load_privatekey( crypto.FILETYPE_PEM, ca_private_key) issue_date = datetime.datetime.now() cs.set_notBefore( issue_date.strftime("%Y%m%d%H%M%SZ").encode("ascii")) issue_date_end = issue_date + datetime.timedelta(days=30) cs.set_notAfter( issue_date_end.strftime("%Y%m%d%H%M%SZ").encode("ascii")) cs.set_subject(req.get_subject()) cs.set_pubkey(crypto_public_key) cs.sign(crypto_private_key, "sha1") with open(f'CS/CA/{cs.get_subject().CN}_Cs.cs', 'wb+') as f: f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cs)) print(f"sending cs to {sid}") await ca.send(sid, 'recv_cs', crypto.dump_certificate(crypto.FILETYPE_PEM, cs)) else: # close connection await ca.terminate_connection(sid) else: await ca.terminate_connection(sid)
def test_issue_certificate_with_csr(self): """ Tests issuance of a certificate """ cmd = issueCertificate.issueCertificateCmd() cmd.csr = "-----BEGIN CERTIFICATE REQUEST-----\nMIIBHjCByQIBADBkMQswCQYDVQQGEwJJTjELMAkGA1UECAwCSFIxETAPBgNVBAcM\nCEd1cnVncmFtMQ8wDQYDVQQKDAZBcGFjaGUxEzARBgNVBAsMCkNsb3VkU3RhY2sx\nDzANBgNVBAMMBnYtMS1WTTBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQD46KFWKYrJ\nF43Y1oqWUfrl4mj4Qm05Bgsi6nuigZv7ufiAKK0nO4iJKdRa2hFMUvBi2/bU3IyY\nNvg7cdJsn4K9AgMBAAGgADANBgkqhkiG9w0BAQUFAANBAIta9glu/ZSjA/ncyXix\nyDOyAKmXXxsRIsdrEuIzakUuJS7C8IG0FjUbDyIaiwWQa5x+Lt4oMqCmpNqRzaGP\nfOo=\n-----END CERTIFICATE REQUEST-----" cmd.provider = 'root' response = self.apiclient.issueCertificate(cmd) self.assertTrue(response.privatekey is None) self.assertTrue(len(response.cacertificates) > 0) self.assertTrue(len(response.certificate) > 0) cert = x509.load_pem_x509_certificate(str(response.certificate), default_backend()) # Validate basic certificate attributes self.assertEqual(cert.signature_hash_algorithm.name, 'sha256') self.assertEqual( cert.subject.get_attributes_for_oid( x509.oid.NameOID.COMMON_NAME)[0].value, 'v-1-VM') # Validate certificate against CA public key global PUBKEY_VERIFY if not PUBKEY_VERIFY: return caCert = x509.load_pem_x509_certificate(str(self.getCaCertificate()), default_backend()) x = X509() x.set_pubkey( load_publickey( FILETYPE_PEM, str(caCert.public_key().public_bytes( serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo)))) verify(x, cert.signature, cert.tbs_certificate_bytes, cert.signature_hash_algorithm.name)
# This file was *autogenerated* from the file solve.sage from sage.all_cmdline import * # import sage library _sage_const_2 = Integer(2) _sage_const_1 = Integer(1) _sage_const_0 = Integer(0) import OpenSSL.crypto as crypto from factordb.factordb import FactorDB key = open("pubkey.pem", "rb").read() message = open("message.txt", "rb").read() key = crypto.load_publickey(crypto.FILETYPE_PEM, key) numbers = key.to_cryptography_key().public_numbers() N = numbers.n E = numbers.e C = int(message) def fermat(n): a = isqrt(n) while True: b = a**_sage_const_2 - n if b > _sage_const_0 and b.is_square(): p = int(str(a - isqrt(b))) return p, n / p a += _sage_const_1
def convertPEMtoDER(key): return crypto.dump_publickey( crypto.FILETYPE_ASN1, crypto.load_publickey(crypto.FILETYPE_PEM, key))
def get_server_public(): pem_str = base64.b64decode(os.getenv('BUNQ_SERVER_PUBLIC_KEY')) if pem_str: return crypto.load_publickey(crypto.FILETYPE_PEM, pem_str) raise Exception("Server public key not found. This should have been " + "set in environment variable BUNQ_SERVER_PUBLIC_KEY")
def get_public_key(): private_key = get_private_key() pem = crypto.dump_publickey(crypto.FILETYPE_PEM, private_key) return crypto.load_publickey(crypto.FILETYPE_PEM, pem)
def check_ca(): #检查文件夹 for dir in (cert_dir, sub_certdir): if os.path.exists(dir): if not os.path.isdir(dir): os.remove(dir) os.mkdir(dir) else: os.mkdir(dir) #检查 CA 证书 if not os.path.exists(ca_keyfile): logging.error('CAkey.pem 不存在,清空 certs 文件夹。') any( os.remove(x) for x in glob.glob(os.path.join(sub_certdir, '*.crt'))) if GC.LISTEN_CHECKSYSCA and sys.platform.startswith('win'): logging.warning('CAkey.pem 不存在,将从系统证书中删除无效的 CA 证书') else: logging.warning('删除功能未启用或未支持,请自行删除 [%s CA] 证书' % ca_vendor) dump_ca() global ca_privatekey, ca_subject, sub_publickey, ca_thumbprint with open(ca_keyfile, 'rb') as fp: content = fp.read() ca = crypto.load_certificate(crypto.FILETYPE_PEM, content) ca_privatekey = crypto.load_privatekey(crypto.FILETYPE_PEM, content) ca_subject = ca.get_subject() ca_thumbprint = ca.digest('sha1') ca_certerror = True if os.path.exists(ca_certfile): with open(ca_certfile, 'rb') as fp: if fp.read() in content: ca_certerror = False if ca_certerror: with open(ca_certfile, 'wb') as fp: fp.write(crypto.dump_certificate(crypto.FILETYPE_PEM, ca)) #检查系统 CA 证书 if GC.LISTEN_CHECKSYSCA and import_ca() != 0: logging.warning( 'install root certificate failed, Please run as administrator/root/sudo' ) #检查伪造网站密钥 if os.path.exists(sub_keyfile): with open(sub_keyfile, 'rb') as fp: content = fp.read() sub_publickey = crypto.load_publickey(crypto.FILETYPE_PEM, content) else: dump_subkey() sub_publickey_str = crypto.dump_publickey(crypto.FILETYPE_PEM, sub_publickey) #检查伪造网站证书 certfiles = glob.glob(os.path.join(sub_certdir, '*.crt')) if certfiles: filename = random.choice(certfiles) with open(filename, 'rb') as fp: content = fp.read() cert = crypto.load_certificate(crypto.FILETYPE_PEM, content) if not verify_certificate( ca, cert) or (sub_publickey_str != crypto.dump_publickey( crypto.FILETYPE_PEM, cert.get_pubkey())): logging.error('Certs mismatch, delete Certs.') any(os.remove(x) for x in certfiles)
def check_authorized(signature, public_key, payload): """Convert PEM encoded public key to a format palatable for pyOpenSSL.""" pkey_public_key = load_publickey(FILETYPE_PEM, public_key) certificate = X509() certificate.set_pubkey(pkey_public_key) verify(certificate, signature, payload, str('sha1'))
def sign_item(data, id): public_key = mongo.db.users.find({'id': id})['public_key'] key = crypto.load_publickey(crypto.FILETYPE_PEM, public_key) return crypto.sign(key, data, b"sha256")
def find_variables(text): """ This is used to detect variables in a given file, or handle a given \ pubkey. :param text: The string to pull the variables from. :return: A Generator for an RSA letter variable and its value. """ # First, check if this is a public key file. beginning_pubkey = re.search("^-----BEGIN.*?-----\s", text, re.MULTILINE | re.DOTALL) ending_pubkey = re.search("-----END.*?-----\s*$", text, re.MULTILINE | re.DOTALL) if beginning_pubkey and ending_pubkey: pubkey = text[beginning_pubkey.start():ending_pubkey.end()] pubkey = crypto.load_publickey(crypto.FILETYPE_PEM, pubkey) rsakey = pubkey.to_cryptography_key().public_numbers() values = (["n", rsakey.n], ["e", rsakey.e]) for letter, value in values: yield letter, value return # We can assume we won't find any other variables.... matches = [ "N", "exponent", "ciphertext", "ct", "message", "dq", "dp", "d", "p", "phi", "q", "totient", ] for m in matches: match = re.search(r"({0})({1})?\)?\s*[=:]\s*(.*)".format(m[0], m[1:]), text, re.IGNORECASE) if match: letter = match.groups()[0].lower() middle = match.groups()[1] value = match.groups()[-1] if middle: middle = middle.lower() if letter.startswith("m") and middle.startswith("odulus"): letter = "n" if letter.startswith("p") and middle.startswith("hi"): letter = "phi" if letter.startswith("d") and middle.startswith("p"): letter = "dp" if letter.startswith("d") and middle.startswith("q"): letter = "dq" yield letter, value
def convertDERtoPEM(key): return crypto.dump_publickey( crypto.FILETYPE_PEM, crypto.load_publickey(crypto.FILETYPE_ASN1, key))
Import("env") print("Prepare public key") default = "misc/public.key" pubkey_data = "" try: pubkey_data = os.environ["FIRMWARE_PUBLIC_KEY"] except: with open(default, "r") as f: pubkey_data = f.read() if not pubkey_data: env.Append(CPPDEFINES=["-DSIGNED_UPDATES=0"]) exit(0) try: tmp = crypto.load_publickey(crypto.FILETYPE_PEM, pubkey_data) except: exit(0) with open("include/signing_pubkey.h", "w") as f: f.write('#ifndef _GENERATED_PUBKEY_H_\n') f.write('#define _GENERATED_PUBKEY_H_\n') f.write('#include <Arduino.h>\n') f.write('#include "pubkey.h"\n\n') f.write('const char pubkey[] PROGMEM = R"EOF(\n') f.write(pubkey_data) f.write(')EOF";\n') f.write('#endif')
ffi as _ffi, lib as _lib) import M2Crypto #following data are in 9th packet #subjectPublicKeyInfo of the 2nd certificate which is used to sign the 1st key = '30820122300d06092a864886f70d01010105000382010f003082010a0282010100b2d805ca1c742db5175639c54a520996e84bd80cf1689f9a422862c3a530537e5511825b037a0d2fe17904c9b496771981019459f9bcf77a9927822db783dd5a277fb2037a9c5325e9481f464fc89d29f8be7956f6f7fdd93a68da8b4b82334112c3c83cccd6967a84211a22040327178b1c6861930f0e5180331db4b5ceeb7ed062aceeb37b0174ef6935ebcad53da9ee9798ca8daa440e25994a1596a4ce6d02541f2a6a26e2063a6348acb44cd1759350ff132fd6dae1c618f59fc9255df3003ade264db42909cd0f3d236f164a8116fbf28310c3b8d6d855323df1bd0fbd8c52954a16977a522163752f16f9c466bef5b509d8ff2700cd447c6f4b3fb0f70203010001'.decode('hex') #encrypted hash of the 1st certificate encHash = '01b9a2f6b47996333035fa09a9fbf7a9937afe51ce0f95a3fb9f80037e1d63a6d0f7044b7198e2f07e104768545b4a5d43c19240ec911a7f90208d6886df74db949bb615e8e10118d41333c119e61e00702ad00ada8758bf70bd641fed22ee59816f8f2a1ddc728d5c37c03faaa6b225ee8ff0872242dfb2f1dccb7e4c66b63f24cf117bfe2ab1edd111aa959ae0d198bfa52723782e22484e065b6ed1b0870af9f6ab31df75cc6e75f3196a951aedf3d8dee807e9eb7ff61f0cfef5cf39729bb8e3fab966b95ef4c0dfb3f327dc327e07ab3b4c3bdb1b91787302cc4272890086dc9b5cef0acc4886a84ccd073e768b38d4c80f51e2da12c343f2893f9a84f3'.decode('hex') #content of 1st certificate cert = '308207b8a00302010202105f4572da7b32a3d03c7666978b37fc25300d06092a864886f70d01010b0500307e310b3009060355040613025553311d301b060355040a131453796d616e74656320436f72706f726174696f6e311f301d060355040b131653796d616e746563205472757374204e6574776f726b312f302d0603550403132653796d616e74656320436c61737320332053656375726520536572766572204341202d204734301e170d3135303932333030303030305a170d3137303932333233353935395a307d310b30090603550406130255533113301106035504080c0a43616c69666f726e69613111300f06035504070c0853616e204a6f736531133011060355040a0c0a654261792c20496e632e31183016060355040b0c0f53697465204f7065726174696f6e733117301506035504030c0e70616765732e656261792e636f6d30820122300d06092a864886f70d01010105000382010f003082010a0282010100b21aea816c8a5a2e2203eeba246e1656c89fa7fdbcf4cfe293db92713292b93526118c48da91297574fd7942674a0c1e9b5e1b80450590a446a9baca472f9c0abe468afaa863f74330472f75a7024046da171248769d4989173ccd7e7bfca6028054655cf31110fc69db59ee97b1390142f7cdd9a12f5edd605552c5dc2371ea9a6d6ed7ab2677147404cf7754d541ddf5298b184c9d495b955927b6989b2d798be29cc936b50412d9fe7f0e25b9890d53d76051c012eb7a1d8b1ace7abce23420fbca5bdba4130af0454af4fbc2d660562fd4e658115900b727f38cfdb96702a3a121c0ba8a707644ab91e53f08568f86b6cd54ead564d993e47b388f15d0e50203010001a3820549308205453082027b0603551d11048202723082026e820c626566722e656261792e6265820c62656e6c2e656261792e6265820c636166722e656261792e63618207656261792e61748207656261792e62658207656261792e63618207656261792e6368820a656261792e636f2e756b8208656261792e636f6d820b656261792e636f6d2e6175820b656261792e636f6d2e686b820b656261792e636f6d2e6d79820b656261792e636f6d2e73678207656261792e64658207656261792e65738207656261792e66728207656261792e69658207656261792e696e8207656261792e69748207656261792e6e6c8207656261792e70688207656261792e706c8207656261792e7275821270616765732e626566722e656261792e6265821270616765732e62656e6c2e656261792e6265821270616765732e636166722e656261792e6361820d70616765732e656261792e6174820d70616765732e656261792e6265820d70616765732e656261792e6361820d70616765732e656261792e6368821070616765732e656261792e636f2e756b820e70616765732e656261792e636f6d821170616765732e656261792e636f6d2e6175821170616765732e656261792e636f6d2e686b821170616765732e656261792e636f6d2e6d79821170616765732e656261792e636f6d2e7367820d70616765732e656261792e6465820d70616765732e656261792e6573820d70616765732e656261792e6672820d70616765732e656261792e6965820d70616765732e656261792e696e820d70616765732e656261792e6974820d70616765732e656261792e6e6c820d70616765732e656261792e7068820d70616765732e656261792e706c820d70616765732e656261792e727530090603551d1304023000300e0603551d0f0101ff0404030205a0301d0603551d250416301406082b0601050507030106082b0601050507030230610603551d20045a30583056060667810c010202304c302306082b06010505070201161768747470733a2f2f642e73796d63622e636f6d2f637073302506082b0601050507020230191a1768747470733a2f2f642e73796d63622e636f6d2f727061301f0603551d230418301680145f60cf619055df8443148a602ab2f57af44318ef302b0603551d1f042430223020a01ea01c861a687474703a2f2f73732e73796d63622e636f6d2f73732e63726c305706082b06010505070101044b3049301f06082b060105050730018613687474703a2f2f73732e73796d63642e636f6d302606082b06010505073002861a687474703a2f2f73732e73796d63622e636f6d2f73732e6372743082017e060a2b06010401d6790204020482016e0482016a0168007700ddeb1d2b7a0d4fa6208b81ad8168707e2e8e9d01d55c888d3d11c4cdb6ecbecc0000014ff9542aaa00000403004830460221008c579fb270d2d17227517161a3e1bd08235f7357912f0509e781abc233100247022100a5e7dfaa35ffd47e06f6d3a241eaeba3d7aabbd2e30cc6990e0cd521a48248fa007500a4b90990b418581487bb13a2cc67700a3c359804f91bdfb8e377cd0ec80ddc100000014ff9542aed000004030046304402205de0ace4e55e1a4130fdef4406f7d48c41aed0f89a7109aa7d3848511551785b02203a0607ac8597ead7a05ba4014f0fcdcbf8e6841981ad06d1fcbfa3971863172000760068f698f81f6482be3a8ceeb9281d4cfc71515d6793d444d10a67acbb4f4ffbc40000014ff9542af50000040300473045022100ff2be0f169e5cfefe582ab4f486e882e3ee63e6e4564657d23f1cfc98212ecab02207020d4cd3ed99efd718414b9deba4654a3d8d2c179d906b21ea792390151033e'.decode('hex') #calculate the SHA256 for later comparison print SHA256.new(cert).hexdigest() pubkey = load_publickey(FILETYPE_ASN1,key) f = open("pub.pem","wb+") f.write(dump_publickey(FILETYPE_PEM, pubkey)) f.close() print "Pubkey: " + str(pubkey.bits()) + " bits,", rsa = _lib.EVP_PKEY_get1_RSA(pubkey._pkey) print str(_lib.RSA_size(rsa)) + " bytes." #Got problem with pyOpenSSL to decrypt so use M2Crypto instead #result = _lib.RSA_public_decrypt(len(encHash),encHash,decHash,rsa,_lib.RSA_PKCS1_PADDING) rsa = M2Crypto.RSA.load_pub_key('pub.pem') decHash = rsa.public_decrypt(encHash,M2Crypto.RSA.no_padding) print "PKCS #1 data of signature\n", decHash.encode('hex') #see rfc 3447 9.2 EMSA-PKCS1-v1_5 nextZero = decHash[2:].find("\x00") + 2 decHash = decHash[nextZero+1:] #asn.1 DER-encoded