Python ecdsa.NIST256p() Examples
The following are 28
code examples of ecdsa.NIST256p().
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
ecdsa
, or try the search function
.
Example #1
Source File: formats.py From deosorg with GNU General Public License v3.0 | 6 votes |
def _decompress_nist256(pubkey): """ Load public key from the serialized blob. The leading byte least-significant bit is used to decide how to recreate the y-coordinate from the specified x-coordinate. See bitcoin/main.py#L198 (from https://github.com/vbuterin/pybitcointools/) for details. """ if pubkey[:1] in {b'\x02', b'\x03'}: # set by ecdsa_get_public_key33() curve = ecdsa.NIST256p P = curve.curve.p() A = curve.curve.a() B = curve.curve.b() x = util.bytes2num(pubkey[1:33]) beta = pow(int(x * x * x + A * x + B), int((P + 1) // 4), int(P)) p0 = util.bytes2num(pubkey[:1]) y = (P - beta) if ((beta + p0) % 2) else beta point = ecdsa.ellipticcurve.Point(curve.curve, x, y) return ecdsa.VerifyingKey.from_public_point(point, curve=curve, hashfunc=hashfunc)
Example #2
Source File: utils.py From autopush with Mozilla Public License 2.0 | 6 votes |
def extract_jwt(token, crypto_key, is_trusted=False, use_crypto=False): # type: (str, str, bool, bool) -> Dict[str, str] """Extract the claims from the validated JWT. """ # first split and convert the jwt. if not token or not crypto_key: return {} if is_trusted: return VerifyJWT.extract_assertion(token) if use_crypto: return VerifyJWT.validate_and_extract_assertion( token, decipher_public_key(crypto_key.encode('utf8'))) else: key = ecdsa.VerifyingKey.from_string( base64.urlsafe_b64decode( repad(crypto_key.encode('utf8')))[-64:], curve=ecdsa.NIST256p ) return jwt.decode(token, dict(keys=[key]), options=dict( verify_aud=False, verify_sub=False, verify_exp=False, ))
Example #3
Source File: test_integration.py From autopush with Mozilla Public License 2.0 | 6 votes |
def test_with_key(self): private_key = ecdsa.SigningKey.generate(curve=ecdsa.NIST256p) claims = {"aud": "http://example.com", "exp": int(time.time()) + 86400, "sub": "a@example.com"} vapid = _get_vapid(private_key, claims) pk_hex = vapid['crypto-key'] chid = str(uuid.uuid4()) client = Client("ws://localhost:9010/") yield client.connect() yield client.hello() yield client.register(chid=chid, key=pk_hex) # Send an update with a properly formatted key. yield client.send_notification(vapid=vapid) # now try an invalid key. new_key = ecdsa.SigningKey.generate(curve=ecdsa.NIST256p) vapid = _get_vapid(new_key, claims) yield client.send_notification( vapid=vapid, status=401) yield self.shut_down(client)
Example #4
Source File: espsecure.py From esptool with GNU General Public License v2.0 | 6 votes |
def generate_signing_key(args): if os.path.exists(args.keyfile): raise esptool.FatalError("ERROR: Key file %s already exists" % args.keyfile) if args.version == "1": """ Generate an ECDSA signing key for signing secure boot images (post-bootloader) """ sk = ecdsa.SigningKey.generate(curve=ecdsa.NIST256p) with open(args.keyfile, "wb") as f: f.write(sk.to_pem()) print("ECDSA NIST256p private key in PEM format written to %s" % args.keyfile) elif args.version == "2": """ Generate a RSA 3072 signing key for signing secure boot images """ private_key = rsa.generate_private_key( public_exponent=65537, key_size=3072, backend=default_backend() ).private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.NoEncryption() ).decode() with open(args.keyfile, "wb") as f: f.write(private_key) print("RSA 3072 private key in PEM format written to %s" % args.keyfile)
Example #5
Source File: formats.py From trezor-agent with GNU Lesser General Public License v3.0 | 6 votes |
def _decompress_nist256(pubkey): """ Load public key from the serialized blob. The leading byte least-significant bit is used to decide how to recreate the y-coordinate from the specified x-coordinate. See bitcoin/main.py#L198 (from https://github.com/vbuterin/pybitcointools/) for details. """ if pubkey[:1] in {b'\x02', b'\x03'}: # set by ecdsa_get_public_key33() curve = ecdsa.NIST256p P = curve.curve.p() A = curve.curve.a() B = curve.curve.b() x = util.bytes2num(pubkey[1:33]) beta = pow(int(x * x * x + A * x + B), int((P + 1) // 4), int(P)) p0 = util.bytes2num(pubkey[:1]) y = (P - beta) if ((beta + p0) % 2) else beta point = ecdsa.ellipticcurve.Point(curve.curve, x, y) return ecdsa.VerifyingKey.from_public_point(point, curve=curve, hashfunc=hashfunc) else: return None
Example #6
Source File: ecc.py From scalyr-agent-2 with Apache License 2.0 | 6 votes |
def getPointByteSize(point): """Convert the point or curve bit size to bytes""" curveMap = {ecdsa.NIST256p.curve: 256//8, ecdsa.NIST384p.curve: 384//8, ecdsa.NIST521p.curve: (521+7)//8, ecdsa.SECP256k1.curve: 256//8} if ecdsaAllCurves: curveMap[ecdsa.NIST224p.curve] = 224//8 curveMap[ecdsa.NIST192p.curve] = 192//8 if hasattr(point, 'curve'): if callable(point.curve): return curveMap[point.curve()] else: return curveMap[point.curve] raise ValueError("Parameter must be a curve or point on curve")
Example #7
Source File: u2f.py From privacyidea with GNU Affero General Public License v3.0 | 5 votes |
def sign_challenge(user_priv_key, app_id, client_data, counter, user_presence_byte=b'\x01'): """ This creates a signature for the U2F data. Only used in test scenario The calculation of the signature is described here: https://fidoalliance.org/specs/fido-u2f-v1.0-nfc-bt-amendment-20150514/fido-u2f-raw-message-formats.html#authentication-response-message-success The input_data is a concatenation of: * AppParameter: sha256(app_id) * The user presence [1byte] * counter [4byte] * ChallengeParameter: sha256(client_data) :param user_priv_key: The private key :type user_priv_key: hex string :param app_id: The application id :type app_id: str :param client_data: the stringified JSON :type client_data: str :param counter: the authentication counter :type counter: int :param user_presence_byte: one byte 0x01 :type user_presence_byte: char :return: The DER encoded signature :rtype: hex string """ app_id_hash = sha256(to_bytes(app_id)).digest() client_data_hash = sha256(to_bytes(client_data)).digest() counter_bin = struct.pack(">L", counter) input_data = app_id_hash + user_presence_byte + counter_bin + \ client_data_hash priv_key_bin = binascii.unhexlify(user_priv_key) sk = ecdsa.SigningKey.from_string(priv_key_bin, curve=ecdsa.NIST256p, hashfunc=sha256) signature = sk.sign(input_data) der_sig = der_encode(signature) return hexlify_and_unicode(der_sig)
Example #8
Source File: Crypto.py From neo-python-core with MIT License | 5 votes |
def VerifySignature(message, signature, public_key, unhex=True): """ Verify the integrity of the message. Args: message (str): the message to verify. signature (bytearray): the signature belonging to the message. public_key (ECPoint|bytes): the public key to use for verifying the signature. If `public_key` is of type bytes then it should be raw bytes (i.e. b'\xAA\xBB'). unhex (bool): whether the message should be unhexlified before verifying Returns: bool: True if verification passes. False otherwise. """ if type(public_key) is EllipticCurve.ECPoint: pubkey_x = public_key.x.value.to_bytes(32, 'big') pubkey_y = public_key.y.value.to_bytes(32, 'big') public_key = pubkey_x + pubkey_y if unhex: try: message = binascii.unhexlify(message) except Exception as e: logger.error("could not get m: %s" % e) elif isinstance(message, str): message = message.encode('utf-8') if len(public_key) == 33: public_key = bitcoin.decompress(public_key) public_key = public_key[1:] try: vk = VerifyingKey.from_string(public_key, curve=NIST256p, hashfunc=hashlib.sha256) res = vk.verify(signature, message, hashfunc=hashlib.sha256) return res except Exception as e: pass return False
Example #9
Source File: test_protocol.py From deosorg with GNU General Public License v3.0 | 5 votes |
def test_nist256p1_ecdh(): sk = ecdsa.SigningKey.from_secret_exponent(secexp=1, curve=ecdsa.NIST256p) vk = sk.get_verifying_key() pk = protocol.PublicKey(curve_name=formats.CURVE_NIST256, created=42, verifying_key=vk, ecdh=True) assert repr(pk) == 'GPG public key nist256p1/5811DF46' assert pk.keygrip() == b'\x95\x85.\x91\x7f\xe2\xc3\x91R\xba\x99\x81\x92\xb5y\x1d\xb1\\\xdc\xf0'
Example #10
Source File: test_protocol.py From deosorg with GNU General Public License v3.0 | 5 votes |
def test_nist256p1(): sk = ecdsa.SigningKey.from_secret_exponent(secexp=1, curve=ecdsa.NIST256p) vk = sk.get_verifying_key() pk = protocol.PublicKey(curve_name=formats.CURVE_NIST256, created=42, verifying_key=vk) assert repr(pk) == 'GPG public key nist256p1/F82361D9' assert pk.keygrip() == b'\x95\x85.\x91\x7f\xe2\xc3\x91R\xba\x99\x81\x92\xb5y\x1d\xb1\\\xdc\xf0'
Example #11
Source File: Crypto.py From neo-python with MIT License | 5 votes |
def VerifySignature(message, signature, public_key, unhex=True): """ Verify the integrity of the message. Args: message (hexstr or str): the message to verify. signature (bytearray): the signature belonging to the message. public_key (ECPoint|bytes): the public key to use for verifying the signature. If `public_key` is of type bytes then it should be raw bytes (i.e. b'\xAA\xBB'). unhex (bool): whether the message should be unhexlified before verifying Returns: bool: True if verification passes. False otherwise. """ if type(public_key) is EllipticCurve.ECPoint: pubkey_x = public_key.x.value.to_bytes(32, 'big') pubkey_y = public_key.y.value.to_bytes(32, 'big') public_key = pubkey_x + pubkey_y if unhex: try: message = binascii.unhexlify(message) except binascii.Error: pass elif isinstance(message, str): message = message.encode('utf-8') if len(public_key) == 33: public_key = bitcoin.decompress(public_key) public_key = public_key[1:] try: vk = VerifyingKey.from_string(public_key, curve=NIST256p, hashfunc=hashlib.sha256) res = vk.verify(signature, message, hashfunc=hashlib.sha256) return res except Exception: pass return False
Example #12
Source File: sgx.py From sgx-kms with Apache License 2.0 | 5 votes |
def generate_key_pair(self, key_dir): pub_key_path = os.path.join(key_dir, "public_key.pem") priv_key_path = os.path.join(key_dir, "private_key.pem") if not os.path.exists(pub_key_path) and not os.path.exists(priv_key_path): priv_key = SigningKey.generate(curve=NIST256p) pub_key = priv_key.get_verifying_key() open(priv_key_path, "w").write(priv_key.to_pem()) open(pub_key_path, "w").write(pub_key.to_pem()) else: priv_key = SigningKey.from_pem(open(priv_key_path).read()) pub_key = VerifyingKey.from_pem(open(pub_key_path).read()) pk64 = pub_key.to_string() pk_x, pk_y = pk64[:len(pk64)/2], pk64[len(pk64)/2:] hex_priv_key = priv_key.to_string() hex_sk = hex_priv_key.encode('hex') pk_x = pk_x.encode('hex') pk_y = pk_y.encode('hex') hex_priv_key_out = [hex_sk[i:i + 2]for i in range(0, len(hex_sk), 2)] pk_x_out = [pk_x[i:i + 2] for i in range(0,len(pk_x), 2)] pk_y_out = [pk_y[i:i + 2] for i in range(0,len(pk_y), 2)] pk_x_out.reverse() pk_y_out.reverse() pub_key = "" for i in range(len(pk_x_out)): pub_key = pub_key + pk_x_out[i] for i in range(len(pk_y_out)): pub_key = pub_key + pk_y_out[i] hex_priv_key_out.reverse() priv_key = "" for i in range(len(hex_priv_key_out)): priv_key = priv_key + hex_priv_key_out[i] pub_key = base64.b64encode(pub_key + '\0') priv_key = base64.b64encode(priv_key + '\0') return pub_key , priv_key
Example #13
Source File: test_protocol.py From trezor-agent with GNU Lesser General Public License v3.0 | 5 votes |
def test_nist256p1_ecdh(): sk = ecdsa.SigningKey.from_secret_exponent(secexp=1, curve=ecdsa.NIST256p) vk = sk.get_verifying_key() pk = protocol.PublicKey(curve_name=formats.CURVE_NIST256, created=42, verifying_key=vk, ecdh=True) assert repr(pk) == 'GPG public key nist256p1/5811DF46' assert pk.keygrip() == b'\x95\x85.\x91\x7f\xe2\xc3\x91R\xba\x99\x81\x92\xb5y\x1d\xb1\\\xdc\xf0'
Example #14
Source File: test_protocol.py From trezor-agent with GNU Lesser General Public License v3.0 | 5 votes |
def test_nist256p1(): sk = ecdsa.SigningKey.from_secret_exponent(secexp=1, curve=ecdsa.NIST256p) vk = sk.get_verifying_key() pk = protocol.PublicKey(curve_name=formats.CURVE_NIST256, created=42, verifying_key=vk) assert repr(pk) == 'GPG public key nist256p1/F82361D9' assert pk.keygrip() == b'\x95\x85.\x91\x7f\xe2\xc3\x91R\xba\x99\x81\x92\xb5y\x1d\xb1\\\xdc\xf0'
Example #15
Source File: ecc.py From scalyr-agent-2 with Apache License 2.0 | 5 votes |
def decodeX962Point(data, curve=ecdsa.NIST256p): """Decode a point from a X9.62 encoding""" parser = Parser(data) encFormat = parser.get(1) assert encFormat == 4 bytelength = getPointByteSize(curve) xCoord = bytesToNumber(parser.getFixBytes(bytelength)) yCoord = bytesToNumber(parser.getFixBytes(bytelength)) return ecdsa.ellipticcurve.Point(curve.curve, xCoord, yCoord)
Example #16
Source File: bravecore.py From evesrp with BSD 2-Clause "Simplified" License | 5 votes |
def hex2key(hex_key): key_bytes = unhexlify(hex_key) if len(hex_key) == 64: return SigningKey.from_string(key_bytes, curve=NIST256p, hashfunc=sha256) elif len(hex_key) == 128: return VerifyingKey.from_string(key_bytes, curve=NIST256p, hashfunc=sha256) else: raise ValueError("Key in hex form is of the wrong length.")
Example #17
Source File: espsecure.py From esptool with GNU General Public License v2.0 | 5 votes |
def verify_signature_v1(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: raise esptool.FatalError("Signature block has version %d. This version of espsecure only supports version 0." % sig_version) print("Verifying %d bytes of data" % len(data)) try: if vk.verify(signature, data, hashlib.sha256): print("Signature is valid") else: raise esptool.FatalError("Signature is not valid") except ecdsa.keys.BadSignatureError: raise esptool.FatalError("Signature is not valid")
Example #18
Source File: espsecure.py From esptool with GNU General Public License v2.0 | 5 votes |
def _load_ecdsa_signing_key(keyfile): sk = ecdsa.SigningKey.from_pem(keyfile.read()) if sk.curve != ecdsa.NIST256p: raise esptool.FatalError("Signing key uses incorrect curve. ESP32 Secure Boot only supports NIST256p (openssl calls this curve 'prime256v1") return sk
Example #19
Source File: test_web_validation.py From autopush with Mozilla Public License 2.0 | 5 votes |
def test_null_vapid_header(self): schema = self._make_fut() schema.context["conf"].use_cryptography = True def b64s(content): return base64.urlsafe_b64encode(content).strip(b'=') payload = b'.'.join([b64s("null"), b64s("null")]) # force sign the header, since jws will "fix" the invalid one. sk256p = ecdsa.SigningKey.generate(curve=ecdsa.NIST256p) vk = sk256p.get_verifying_key() key = jwk.construct(sk256p, "ES256") signature = b64s(key.sign(payload)) token = b'.'.join([payload, signature]) crypto_key = b64s(vk.to_string()) self.fernet_mock.decrypt.return_value = ( 'a' * 32) + sha256(utils.base64url_decode(crypto_key)).digest() info = self._make_test_data( body="asdfasdfasdfasdf", path_kwargs=dict( api_ver="v2", token="asdfasdf", ), headers={ "content-encoding": "aes128gcm", "authorization": "vapid k={},t={}".format(crypto_key, token) } ) with pytest.raises(InvalidRequest) as cm: schema.load(info) assert cm.value.status_code == 401 assert cm.value.errno == 109
Example #20
Source File: test_web_validation.py From autopush with Mozilla Public License 2.0 | 5 votes |
def _gen_jwt(self, header, payload): sk256p = ecdsa.SigningKey.generate(curve=ecdsa.NIST256p) vk = sk256p.get_verifying_key() sig = jws.sign(payload, sk256p, algorithm="ES256").strip('=') crypto_key = utils.base64url_encode(vk.to_string()).strip('=') return sig, crypto_key
Example #21
Source File: test_integration.py From autopush with Mozilla Public License 2.0 | 5 votes |
def _get_vapid(key=None, payload=None): if not payload: payload = {"aud": "https://pusher_origin.example.com", "exp": int(time.time()) + 86400, "sub": "mailto:admin@example.com"} if not key: key = ecdsa.SigningKey.generate(curve=ecdsa.NIST256p) vk = key.get_verifying_key() auth = jws.sign(payload, key, algorithm="ES256").strip('=') crypto_key = base64url_encode('\4' + vk.to_string()) return {"auth": auth, "crypto-key": crypto_key, "key": key}
Example #22
Source File: ecc.py From scalyr-agent-2 with Apache License 2.0 | 4 votes |
def getCurveByName(curveName): """Return curve identified by curveName""" curveMap = {'secp256r1':ecdsa.NIST256p, 'secp384r1':ecdsa.NIST384p, 'secp521r1':ecdsa.NIST521p, 'secp256k1':ecdsa.SECP256k1} if ecdsaAllCurves: curveMap['secp224r1'] = ecdsa.NIST224p curveMap['secp192r1'] = ecdsa.NIST192p if curveName in curveMap: return curveMap[curveName] else: raise ValueError("Curve of name '{0}' unknown".format(curveName))
Example #23
Source File: ssh_transport.py From ssh_client with MIT License | 4 votes |
def _get_verifying_key(self, host_key_blob): # Parse the received data from the host_key_blob index, host_key_type = parse_string(host_key_blob, 0) index, curve_name = parse_string(host_key_blob, index) index, host_public_key = parse_string(host_key_blob, index) # Find the expected host key in ~/.ssh/known_hosts expected_host_key_type = None expected_host_public_key = None known_hosts_filename = os.path.expanduser('~/.ssh/known_hosts') for line in open(known_hosts_filename, 'r'): if len(line.strip()) > 0: current_hostname, current_key_type, current_key = line.split(' ') if current_hostname == self.hostname: expected_host_key_type = current_key_type expected_host_public_key = current_key.decode('base64') break # If we *did* find the host key (i.e. we've already connected to this server), check that # everything matches if expected_host_key_type is not None: assert host_key_type == expected_host_key_type, 'Unexpected host key type: %s' % host_key_type assert curve_name == 'nistp256', 'Unknown curve name: %s' % curve_name assert host_key_blob == expected_host_public_key, \ 'Unexpected host public key: %s' % repr(host_key_blob) # Otherwise, if we haven't seen the host key before, prompt the user to see if they're okay with # that else: assert host_key_type == 'ecdsa-sha2-nistp256', 'Unknown host key type: %s' % host_key_type key_fingerprint = hashlib.sha256(host_key_blob).digest().encode('base64') # Remove the base64-added new lines, and the padding '=' characters key_fingerprint = key_fingerprint.replace('\n', '').rstrip('=') print "The authenticity of host '%s' can't be established." % self.hostname print "ECDSA key fingerprint is SHA256:%s." % key_fingerprint answer = raw_input("Are you sure you want to continue connecting (yes/no)?\n").strip() while answer not in ['yes', 'no', '']: answer = raw_input("Please type 'yes' or 'no': ").strip() # Add key to ~/.ssh/known_hosts if answer == 'yes': with open(known_hosts_filename, 'a') as known_hosts_file: host_key_base64 = host_key_blob.encode('base64').replace('\n', '') known_hosts_file.write('%s %s %s\n' % (self.hostname, host_key_type, host_key_base64)) else: assert False, 'Host key verification failed.' # NFI why we need to skip a byte here - I can't find this format documented anywhere. I assume # this is some kind of type indicator. assert host_public_key[0] == '\x04' return ecdsa.VerifyingKey.from_string(host_public_key[1:], curve=ecdsa.NIST256p)
Example #24
Source File: formats.py From trezor-agent with GNU Lesser General Public License v3.0 | 4 votes |
def parse_pubkey(blob): """ Parse SSH public key from given blob. Construct a verifier for ECDSA signatures. The verifier returns the signatures in the required SSH format. Currently, NIST256P1 and ED25519 elliptic curves are supported. """ fp = fingerprint(blob) s = io.BytesIO(blob) key_type = util.read_frame(s) log.debug('key type: %s', key_type) assert key_type in SUPPORTED_KEY_TYPES, key_type result = {'blob': blob, 'type': key_type, 'fingerprint': fp} if key_type == SSH_NIST256_KEY_TYPE: curve_name = util.read_frame(s) log.debug('curve name: %s', curve_name) point = util.read_frame(s) assert s.read() == b'' _type, point = point[:1], point[1:] assert _type == SSH_NIST256_DER_OCTET size = len(point) // 2 assert len(point) == 2 * size coords = (util.bytes2num(point[:size]), util.bytes2num(point[size:])) curve = ecdsa.NIST256p point = ecdsa.ellipticcurve.Point(curve.curve, *coords) def ecdsa_verifier(sig, msg): assert len(sig) == 2 * size sig_decode = ecdsa.util.sigdecode_string vk = ecdsa.VerifyingKey.from_public_point(point, curve, hashfunc) vk.verify(signature=sig, data=msg, sigdecode=sig_decode) parts = [sig[:size], sig[size:]] return b''.join([util.frame(b'\x00' + p) for p in parts]) result.update(point=coords, curve=CURVE_NIST256, verifier=ecdsa_verifier) if key_type == SSH_ED25519_KEY_TYPE: pubkey = util.read_frame(s) assert s.read() == b'' def ed25519_verify(sig, msg): assert len(sig) == 64 vk = ed25519.VerifyingKey(pubkey) vk.verify(sig, msg) return sig result.update(curve=CURVE_ED25519, verifier=ed25519_verify) return result
Example #25
Source File: sgx.py From sgx-kms with Apache License 2.0 | 4 votes |
def generate_key_pair(self): separator = "=" key_dir = None with open("/opt/BarbiE/env.properties") as f: for line in f: if separator in line: name, value = line.split(separator) if name.strip() == "KEY_PAIR_DIR": key_dir = value.strip() pub_key_path = os.path.join(key_dir, "public_key.pem") priv_key_path = os.path.join(key_dir, "private_key.pem") if not os.path.exists(pub_key_path): priv_key = SigningKey.generate(curve=NIST256p) pub_key = priv_key.get_verifying_key() open(priv_key_path,"w").write(priv_key.to_pem()) open(pub_key_path,"w").write(pub_key.to_pem()) else: priv_key = SigningKey.from_pem(open(priv_key_path).read()) pub_key = VerifyingKey.from_pem(open(pub_key_path).read()) pk64 = pub_key.to_string() pk_x, pk_y = pk64[:len(pk64)/2], pk64[len(pk64)/2:] hex_priv_key = priv_key.to_string() hex_sk = hex_priv_key.encode('hex') pk_x = pk_x.encode('hex') pk_y = pk_y.encode('hex') hex_priv_key_out = [hex_sk[i:i + 2]for i in range(0, len(hex_sk), 2)] pk_x_out = [pk_x[i:i + 2] for i in range(0,len(pk_x), 2)] pk_y_out = [pk_y[i:i + 2] for i in range(0,len(pk_y), 2)] pk_x_out.reverse() pk_y_out.reverse() pub_key = "" for i in range(len(pk_x_out)): pub_key = pub_key + pk_x_out[i] for i in range(len(pk_y_out)): pub_key = pub_key + pk_y_out[i] hex_priv_key_out.reverse() priv_key = "" for i in range(len(hex_priv_key_out)): priv_key = priv_key + hex_priv_key_out[i] pub_key = base64.b64encode(pub_key + '\0') priv_key = base64.b64encode(priv_key + '\0') return pub_key , priv_key
Example #26
Source File: formats.py From deosorg with GNU General Public License v3.0 | 4 votes |
def parse_pubkey(blob): """ Parse SSH public key from given blob. Construct a verifier for ECDSA signatures. The verifier returns the signatures in the required SSH format. Currently, NIST256P1 and ED25519 elliptic curves are supported. """ fp = fingerprint(blob) s = io.BytesIO(blob) key_type = util.read_frame(s) log.debug('key type: %s', key_type) assert key_type in SUPPORTED_KEY_TYPES, key_type result = {'blob': blob, 'type': key_type, 'fingerprint': fp} if key_type == SSH_NIST256_KEY_TYPE: curve_name = util.read_frame(s) log.debug('curve name: %s', curve_name) point = util.read_frame(s) assert s.read() == b'' _type, point = point[:1], point[1:] assert _type == SSH_NIST256_DER_OCTET size = len(point) // 2 assert len(point) == 2 * size coords = (util.bytes2num(point[:size]), util.bytes2num(point[size:])) curve = ecdsa.NIST256p point = ecdsa.ellipticcurve.Point(curve.curve, *coords) def ecdsa_verifier(sig, msg): assert len(sig) == 2 * size sig_decode = ecdsa.util.sigdecode_string vk = ecdsa.VerifyingKey.from_public_point(point, curve, hashfunc) vk.verify(signature=sig, data=msg, sigdecode=sig_decode) parts = [sig[:size], sig[size:]] return b''.join([util.frame(b'\x00' + p) for p in parts]) result.update(point=coords, curve=CURVE_NIST256, verifier=ecdsa_verifier) if key_type == SSH_ED25519_KEY_TYPE: pubkey = util.read_frame(s) assert s.read() == b'' def ed25519_verify(sig, msg): assert len(sig) == 64 vk = ed25519.VerifyingKey(pubkey) vk.verify(sig, msg) return sig result.update(curve=CURVE_ED25519, verifier=ed25519_verify) return result
Example #27
Source File: u2f.py From privacyidea with GNU Affero General Public License v3.0 | 4 votes |
def check_response(user_pub_key, app_id, client_data, signature, counter, user_presence_byte=b'\x01'): """ Check the ECDSA Signature with the given pubkey. The signed data is constructed from * app_id * user_presence_byte * counter and * client_data :param user_pub_key: The Application specific public key :type user_pub_key: hex string :param app_id: The AppID for this challenge response :type app_id: str :param client_data: The ClientData :type client_data: str :param counter: A counter :type counter: int :param user_presence_byte: User presence byte :type user_presence_byte: byte :param signature: The signature of the authentication request :type signature: hex string :return: """ res = True app_id_hash = sha256(to_bytes(app_id)).digest() client_data_hash = sha256(to_bytes(client_data)).digest() user_pub_key_bin = binascii.unhexlify(user_pub_key) counter_bin = struct.pack(">L", counter) signature_bin = binascii.unhexlify(signature) input_data = app_id_hash + user_presence_byte + counter_bin \ + client_data_hash # The first byte 0x04 only indicates, that the public key is in the # uncompressed format x: 32 byte, y: 32byte user_pub_key_bin = user_pub_key_bin[1:] signature_bin_asn = der_decode(signature_bin) vkey = ecdsa.VerifyingKey.from_string(user_pub_key_bin, curve=ecdsa.NIST256p, hashfunc=sha256) try: vkey.verify(signature_bin_asn, input_data) except ecdsa.BadSignatureError: log.error("Bad signature for app_id {0!s}".format(app_id)) res = False return res
Example #28
Source File: manifest.py From docker-registry-client with Apache License 2.0 | 4 votes |
def sign(manifest, key=None): m = assign({}, manifest) try: del m['signatures'] except KeyError: pass assert len(m) > 0 manifest_json = json.dumps(m, sort_keys=True) if key is None: key = ecdsa.SigningKey.generate(curve=ecdsa.NIST256p) manifest64 = _urlsafe_b64encode(manifest_json) format_length = manifest_json.rfind('}') format_tail = manifest_json[format_length:] protected_json = json.dumps({ 'formatLength': format_length, 'formatTail': _urlsafe_b64encode(format_tail) }) protected64 = _urlsafe_b64encode(protected_json) point = key.privkey.public_key.point data = { 'key': key, 'header': { 'alg': 'ES256' } } jws.header.process(data, 'sign') sig = data['signer']("%s.%s" % (protected64, manifest64), key) signatures = [{ 'header': { 'jwk': { 'kty': 'EC', 'crv': 'P-256', 'x': _num_to_base64(point.x()), 'y': _num_to_base64(point.y()) }, 'alg': 'ES256' }, 'signature': _urlsafe_b64encode(sig), 'protected': protected64 }] return ( manifest_json[:format_length] + ', "signatures": ' + json.dumps(signatures) + format_tail )