Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def initFromPath(self, path):
'Will initialize the directory from the path supplied'
import cPickle
data = None
with open(path,'r') as f:
data = cPickle.load(f)
assert data != None, "Expected some data, did not load any."
priv_key_from_pem = lambda x: crypto.load_privatekey(crypto.FILETYPE_PEM, x)
for userName, keyTuple in data['users'].iteritems():
self.users[userName] = User(userName, directory=self,
ecdsaSigningKey=ecdsa.SigningKey.from_pem(keyTuple[0]),
rsaSigningKey=priv_key_from_pem(keyTuple[1]))
self.users[userName].tags = keyTuple[2]
for orgName, tuple in data['organizations'].iteritems():
org = Organization(orgName, ecdsaSigningKey=ecdsa.SigningKey.from_pem(tuple[0]),
rsaSigningKey=priv_key_from_pem(tuple[0]))
org.signedCert = crypto.load_certificate(crypto.FILETYPE_PEM, tuple[2])
org.networks = [Network[name] for name in tuple[3]]
self.organizations[orgName] = org
for nat, cert_as_pem in data['nats'].iteritems():
self.ordererAdminTuples[nat] = crypto.load_certificate(crypto.FILETYPE_PEM, cert_as_pem)
def verify_signature(args):
""" Verify a previously signed binary image, using the ECDSA public key """
key_data = args.keyfile.read()
if b"-BEGIN EC PRIVATE KEY" in key_data:
sk = ecdsa.SigningKey.from_pem(key_data)
vk = sk.get_verifying_key()
elif b"-BEGIN PUBLIC KEY" in key_data:
vk = ecdsa.VerifyingKey.from_pem(key_data)
elif len(key_data) == 64:
vk = ecdsa.VerifyingKey.from_string(key_data,
curve=ecdsa.NIST256p)
else:
raise esptool.FatalError("Verification key does not appear to be an EC key in PEM format or binary EC public key data. Unsupported")
if vk.curve != ecdsa.NIST256p:
raise esptool.FatalError("Public key uses incorrect curve. ESP32 Secure Boot only supports NIST256p (openssl calls this curve 'prime256v1")
binary_content = args.datafile.read()
data = binary_content[0:-68]
sig_version, signature = struct.unpack("I64s", binary_content[-68:])
if sig_version != 0:
def load_pem(cls, pem_string):
return cls(ecdsa.SigningKey.from_pem(pem_string, hashfunc=cls.HASHFUNC_NAME))
def verify_signature(args):
""" Verify a previously signed binary image, using the ECDSA public key """
key_data = args.keyfile.read()
if b"-BEGIN EC PRIVATE KEY" in key_data:
sk = ecdsa.SigningKey.from_pem(key_data)
vk = sk.get_verifying_key()
elif b"-BEGIN PUBLIC KEY" in key_data:
vk = ecdsa.VerifyingKey.from_pem(key_data)
elif len(key_data) == 64:
vk = ecdsa.VerifyingKey.from_string(key_data,
curve=ecdsa.NIST256p)
else:
raise esptool.FatalError("Verification key does not appear to be an EC key in PEM format or binary EC public key data. Unsupported")
if vk.curve != ecdsa.NIST256p:
raise esptool.FatalError("Public key uses incorrect curve. ESP32 Secure Boot only supports NIST256p (openssl calls this curve 'prime256v1")
binary_content = args.datafile.read()
data = binary_content[0:-68]
sig_version, signature = struct.unpack("I64s", binary_content[-68:])
if sig_version != 0:
def __init__(self):
self.sk = {}
# Loading signature keys to memory
for keyid, private_key in settings.CUP_PEM_KEYS.iteritems():
self.sk[keyid] = SigningKey.from_pem(open(private_key).read())
def load_privkey_pem(filename):
return ecdsa.SigningKey.from_pem(open(filename, 'r').read().strip())
if isinstance(key, ecdsa.SigningKey) or \
isinstance(key, ecdsa.VerifyingKey):
return key
if isinstance(key, string_types):
if isinstance(key, text_type):
key = key.encode('utf-8')
# Attempt to load key. We don't know if it's
# a Signing Key or a Verifying Key, so we try
# the Verifying Key first.
try:
key = ecdsa.VerifyingKey.from_pem(key)
except ecdsa.der.UnexpectedDER:
key = ecdsa.SigningKey.from_pem(key)
else:
raise TypeError('Expecting a PEM-formatted key.')
return key
cryptoBigNumDecode(jwk['d']),
cryptoBigNumDecode(jwk['p']),
cryptoBigNumDecode(jwk['q'])])
""" JWK syntax checking... """
cryptoBigNumDecode(jwk['dp'])
cryptoBigNumDecode(jwk['dq'])
cryptoBigNumDecode(jwk['qi'])
elif keyType == 'EC':
self.nativePrivateKey = EC.from_string(base64UrlDecode(jwk['d']),getEcCurve(jwk['crv']))
else:
raise ValueError('Unsupported key type: "' + keyType + '"');
else:
if ' RSA ' in privateKeyString:
self.nativePrivateKey = RSA.importKey(privateKeyString)
else:
self.nativePrivateKey = EC.from_pem(privateKeyString)
"""
Set default signature algorithm
"""
if self.isRSA():
self.algorithm = 'RS256'
else:
self.algorithm = 'ES256'
if slot < 1 or slot > SLOTS:
raise Exception("Invalid slot")
if is_pem:
print("Paste ECDSA private key in PEM format and press Enter:")
print("(blank private key removes the signature on given index)")
pem_key = ""
while True:
key = input()
pem_key += key + "\n"
if key == "":
break
if pem_key.strip() == "":
# Blank key,let's remove existing signature from slot
return modify(data, slot, 0, b"\x00" * 64)
key = ecdsa.SigningKey.from_pem(pem_key)
else:
print("Paste SECEXP (in hex) and press Enter:")
print("(blank private key removes the signature on given index)")
secexp = input()
if secexp.strip() == "":
# Blank key,let's remove existing signature from slot
return modify(data, slot, 0, b"\x00" * 64)
key = ecdsa.SigningKey.from_secret_exponent(
secexp=int(secexp, 16),
curve=ecdsa.curves.SECP256k1,
hashfunc=hashlib.sha256,
)
to_sign = get_header(data, zero_signatures=True)
# Locate proper index of current signing key
def get_compressed_public_key_from_pem(pem):
vks = SigningKey.from_pem(pem).get_verifying_key().to_string()
bts = binascii.hexlify(vks)
compressed = compress_key(bts)
return compressed