本文整理匯總了Python中ecdsa.NIST256p方法的典型用法代碼示例。如果您正苦於以下問題:Python ecdsa.NIST256p方法的具體用法?Python ecdsa.NIST256p怎麽用?Python ecdsa.NIST256p使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類ecdsa
的用法示例。
在下文中一共展示了ecdsa.NIST256p方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: extract_jwt
# 需要導入模塊: import ecdsa [as 別名]
# 或者: from ecdsa import NIST256p [as 別名]
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,
))
示例2: test_with_key
# 需要導入模塊: import ecdsa [as 別名]
# 或者: from ecdsa import NIST256p [as 別名]
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)
示例3: generate_signing_key
# 需要導入模塊: import ecdsa [as 別名]
# 或者: from ecdsa import NIST256p [as 別名]
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)
示例4: getPointByteSize
# 需要導入模塊: import ecdsa [as 別名]
# 或者: from ecdsa import NIST256p [as 別名]
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")
示例5: _decompress_nist256
# 需要導入模塊: import ecdsa [as 別名]
# 或者: from ecdsa import NIST256p [as 別名]
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
示例6: _decompress_nist256
# 需要導入模塊: import ecdsa [as 別名]
# 或者: from ecdsa import NIST256p [as 別名]
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)
示例7: sign_challenge
# 需要導入模塊: import ecdsa [as 別名]
# 或者: from ecdsa import NIST256p [as 別名]
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)
示例8: _get_vapid
# 需要導入模塊: import ecdsa [as 別名]
# 或者: from ecdsa import NIST256p [as 別名]
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}
示例9: _gen_jwt
# 需要導入模塊: import ecdsa [as 別名]
# 或者: from ecdsa import NIST256p [as 別名]
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
示例10: test_null_vapid_header
# 需要導入模塊: import ecdsa [as 別名]
# 或者: from ecdsa import NIST256p [as 別名]
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
示例11: _load_ecdsa_signing_key
# 需要導入模塊: import ecdsa [as 別名]
# 或者: from ecdsa import NIST256p [as 別名]
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
示例12: verify_signature_v1
# 需要導入模塊: import ecdsa [as 別名]
# 或者: from ecdsa import NIST256p [as 別名]
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")
示例13: hex2key
# 需要導入模塊: import ecdsa [as 別名]
# 或者: from ecdsa import NIST256p [as 別名]
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.")
示例14: decodeX962Point
# 需要導入模塊: import ecdsa [as 別名]
# 或者: from ecdsa import NIST256p [as 別名]
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)
示例15: getCurveByName
# 需要導入模塊: import ecdsa [as 別名]
# 或者: from ecdsa import NIST256p [as 別名]
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))