def on_connect(agent): keys = yield agent.requestIdentities() # if the key is found in ssh-agent, the raw public key (32 bytes), and the # key comment as returned from ssh-agent key_data = None key_comment = None for blob, comment in keys: raw = _unpack(blob) algo = raw[0] if algo == u'ssh-ed25519': algo, _pubkey = raw if _pubkey == pubkey: key_data = _pubkey key_comment = comment.decode('utf8') break agent.transport.loseConnection() if key_data: key = signing.VerifyKey(key_data) returnValue(cls(key, key_comment, reactor)) else: raise Exception("Ed25519 key not held in ssh-agent")
def _verify_signify_ed25519_signature(pubkey_file, signature_file, message): """ Verify a Ed25519 signature created with OpenBSD signify. This will raise a `nacl.exceptions.BadSignatureError` if the signature is bad and return silently when the signature is good. Usage: 1. Create a signature: signify-openbsd -S -s ~/.signify/crossbario-trustroot.sec -m .profile 2. Verify the signature from autobahn.wamp import cryptosign with open('.profile', 'rb') as f: message = f.read() cryptosign._verify_signify_ed25519_signature('.signify/crossbario-trustroot.pub', '.profile.sig', message) http://man.openbsd.org/OpenBSD-current/man1/signify.1 """ pubkey = _read_signify_ed25519_pubkey(pubkey_file) verify_key = signing.VerifyKey(pubkey) sig = _read_signify_ed25519_signature(signature_file) verify_key.verify(message, sig)
def get(self, request): gks = db.get('gks') stream = server.getps(db.get('gkfp')) gke = db.get('gke') box = pubfool.Box(gke, gke.public_key) hits = list() for post in stream: valid = True # Valid signature, will be flipped to False on error try: post = json.loads(box.decrypt(debase(post['encrypted']), debase(post['nonce'])).decode()) print(post) except Exception: # Multiple exceptions can happen which can show malformed message, such as non-UTF8 characters, bad JSON, bad nonce, bad ciphertext, etc. just miss and move on continue try: gks.verify_key.verify(post['msg'].encode(), debase(post['sig'])) uks = signfool.VerifyKey(post['gangsta']['edpub'].encode(), encoder=b64) uks.verify(post['msg'].encode(), debase(post['usig'])) post['KH'] = base64.b64encode(whirlpool(post['gangsta']['edpub'].encode()+post['gangsta']['cvpub'].encode())).decode() except BadSignatureError: valid = False except Exception: continue if valid: hits.append(post) pass pass hits.reverse() ctx = dict(hits=hits) return render(request, 'stream.get.html', ctx)
def FromBytes(cls, key_bytes: bytes) -> IPublicKey: """ Construct class from key bytes. Args: key_bytes (bytes): Key bytes Returns: IPublicKey: IPublicKey object Raises: ValueError: If key bytes are not valid """ # Remove the 0x00 prefix if present because nacl requires 32-byte length if (len(key_bytes) == cls.CompressedLength() and key_bytes[0] == BytesUtils.ToInteger(Ed25519KeysConst.PUB_KEY_PREFIX)): key_bytes = key_bytes[1:] # nacl doesn't check if the point lies on curve try: ed25519_lib.point_decode(key_bytes) except ValueError as ex: raise ValueError("Invalid public key bytes") from ex try: return cls(signing.VerifyKey(key_bytes)) except (exceptions.RuntimeError, exceptions.ValueError) as ex: raise ValueError("Invalid public key bytes") from ex
def from_raw_ed25519_public_key(cls, raw_public_key: bytes) -> "Keypair": """Generate a :class:`Keypair` object from ed25519 public key raw bytes. :param raw_public_key: ed25519 public key raw bytes :return: A new :class:`Keypair` instance derived by the ed25519 public key raw bytes """ verify_key = ed25519.VerifyKey(raw_public_key) return cls(verify_key)
def encrypt_secret(self, node_id, value): key = base58.b58decode(node_id) pk = signing.VerifyKey(key) encryption_key = pk.to_curve25519_public_key() box = public.SealedBox(encryption_key) result = box.encrypt(value.encode()) return binascii.hexlify(result).decode()
def deserialise(stream): # Read verification key bytes_vkey = stream.read(32) verification_key = signing.VerifyKey(bytes_vkey) # Read public key bytes_pkey = stream.read(32) public_key = public.PublicKey(bytes_pkey) # Return a new instance return InstanceReference(verification_key, public_key)
def is_sha2_signature_valid(message, signature): """ Verify sha2 signature validity. :param signature: the signature to be checked :param message: message to check the signature against :return: bool, whether the signature is valid for the message """ parse_message = IrohaCrypto.get_payload_to_be_signed(message) signature_bytes = binascii.unhexlify(signature.signature) public_key = ed25519_sha2.VerifyKey(binascii.unhexlify(signature.public_key)[3:]) valid_message = ed25519_sha2.VerifyKey.verify(public_key, parse_message, signature_bytes) if valid_message == parse_message: return True return False
def perform_handshake() -> signing.VerifyKey: # Get the peer's ID handshake = socket.recv(96) verify = signing.VerifyKey(handshake[64:]) try: if verify.verify(handshake) == handshake[64:]: socket.send(id_proof) return verify else: socket.send(b"Handshake failed: did not sign key") raise nacl.exceptions.BadSignatureError except nacl.exceptions.BadSignatureError: socket.send(b"Handshake failed: bad sig") raise
def verify_transaction(transaction): try: key = signing.VerifyKey(transaction["from"], encoder=encoding.HexEncoder) except CryptoValueError: return False except TypeError: breakpoint() signature = transaction["signature"] unsigned_transaction = strip_key(transaction, "signature") encoded_transaction = encode(unsigned_transaction) try: return key.verify(encoded_transaction, signature) except BadSignatureError: return False
def from_ssh_data(cls, keydata): """ Load an Ed25519 key from SSH key file. The key file can be a (private) signing key (from a SSH private key file) or a (public) verification key (from a SSH public key file). A private key file must be passphrase-less. """ SSH_BEGIN = u'-----BEGIN OPENSSH PRIVATE KEY-----' if keydata.startswith(SSH_BEGIN): # OpenSSH private key keydata, comment = _read_ssh_ed25519_privkey(keydata) key = signing.SigningKey(keydata, encoder=encoding.RawEncoder) else: # OpenSSH public key keydata, comment = _read_ssh_ed25519_pubkey(keydata) key = signing.VerifyKey(keydata) return cls(key, comment)
def eddsa(public=None, private=None): if public is None: private = signing.SigningKey.generate() public = private.verify_key elif not isinstance(public, signing.VerifyKey): public = signing.VerifyKey(public.encode(), encoder=encoding.Base32Encoder) def sign(msg): sig = private.sign(msg).signature return sig def keys(): return public.encode(encoder=encoding.Base32Encoder).decode(), private def verify(msg, sig): return public.verify(msg, sig) return sign, verify, keys
def get(self, request, key): if key == 'self': key = db.get('user-edkeys').verify_key.encode(encoder=b64) key = quote(key) return redirect(to="/feeds/{key}".format(key=key)) stream = server.HTTP().POST('/get/feed', {'key': key}) key = signfool.VerifyKey(key, b64) hits = list() for feed in stream: valid = True try: key.verify(feed['message'].encode(), debase(feed['sig'])) except Exception: valid = False if valid: hits.append(feed['message']) hits.reverse() ctx = dict(hits=hits, key=key.encode(encoder=b64)) return render(request, 'feeds.get.html', ctx)
def from_ssh_key(cls, filename): """ Load an Ed25519 key from a SSH key file. The key file can be a (private) signing key (from a SSH private key file) or a (public) verification key (from a SSH public key file). A private key file must be passphrase-less. """ SSH_BEGIN = u'-----BEGIN OPENSSH PRIVATE KEY-----' with open(filename, 'rb') as f: keydata = f.read().decode('utf-8').strip() if keydata.startswith(SSH_BEGIN): # OpenSSH private key keydata, comment = _read_ssh_ed25519_privkey(keydata) key = signing.SigningKey(keydata, encoder=encoding.RawEncoder) else: # OpenSSH public key keydata, comment = _read_ssh_ed25519_pubkey(keydata) key = signing.VerifyKey(keydata) return cls(key, comment)
def encrypt_secret(self, node_id: str, value: str) -> str: """encrypt value with the public key of the node identity by node_id use this method to generate the content of 'secret_env' argument of the create method Args: node_id(str): target node ID value(str): value to encrypt node_id: str: value: str: Returns: str: encrypted string """ key = base58.b58decode(node_id) pk = signing.VerifyKey(key) encryption_key = pk.to_curve25519_public_key() box = public.SealedBox(encryption_key) result = box.encrypt(value.encode()) return binascii.hexlify(result).decode()
def __init__(self, public_key: bytes): # Passing in a bytearray for public_key passes the type annotation checker, but fails an isinstance check # inside verify key, so we cast to bytes just in case. self._verify_key = signing.VerifyKey(bytes(public_key))
def __init__(self, public_key: bytes): self._verify_key = signing.VerifyKey(public_key)
#!/usr/bin/env python3 import argparse from nacl import signing, encoding import os parser = argparse.ArgumentParser() parser.add_argument( '--key', help='location of verifying key file, default ./keys/verify') parser.add_argument('file', nargs='+', help='files to verify') args = parser.parse_args() if args.key is None: args.key = os.path.dirname(os.path.realpath(__file__)) + "/keys/verify" verify_key_f = os.open(args.key, os.O_RDONLY) verify_key_hex = os.read(verify_key_f, 64) os.close(verify_key_f) verify_key = signing.VerifyKey(verify_key_hex, encoder=encoding.HexEncoder) for arg in args.file: with open(arg, "rb") as f: verified = verify_key.verify(f.read()) with open(arg + ".verified", "wb") as f: f.write(verified)
import json from base64 import b64decode from nacl import signing priv_val = json.load(open('priv_validator.json')) # The *amino type* 954568A3288910 is 64 bytes long, where # raw 32-byte priv key are concatenated to raw 32-byte pub key. raw_key = b64decode(priv_val['priv_key']['value']) signing_key_bytes, verifying_key_bytes = raw_key[:32], raw_key[32:] signing_key = signing.SigningKey(signing_key_bytes) verify_key = signing.VerifyKey(verifying_key_bytes) signed = signing_key.sign(b'I love cats.') # Will raise nacl.exceptions.BadSignatureError if the signature check fails verify_key.verify(signed) # The following code will raise the exception. # signing.VerifyKey(verifying_key_bytes[:31] + b'\x00').verify(signed)
from nacl.encoding import Base64Encoder from nacl import signing signingKey = signing.SigningKey.generate() verifyKey = signingKey.verify_key.encode(encoder=Base64Encoder) signiture = signingKey.sign(b'This is a signed message.', encoder=Base64Encoder) print("Your signed message: {}".format(signiture)) print("Verification key: {}".format(verifyKey)) verifier = signing.VerifyKey(verifyKey, encoder=Base64Encoder) try: verifier.verify(b'This is a signed message,' , signedMessage, encoder=Base64Encoder): print("Message verrified.") except: print("nope")
def pk_of_pkstr(pkstr): """ str -> VerifyKey Return the verify key object from the public key in string """ return nas.VerifyKey(pkstr.encode(),encoder=nae.HexEncoder)
from nacl import encoding, signing # Process # 1. First, our unencrypted, plaintext data is hashed(prevents tampering). # 2. Then the hash is encrypted using the private key. # 3. Then we attach (concatenate) the encrypted hash to the data. # Generating keys bitu_private_key= signing.SigningKey.generate() bitu_public_key = bitu_private_key.verify_key # creating hex of public key bitu_public_key_hex = bitu_public_key.encode(encoder=encoding.HexEncoder) # now sign a document signed = bitu_private_key.sign(b"Send $37 to Mama") verify_key = signing.VerifyKey(bitu_public_key_hex, encoder=encoding.HexEncoder) try: print(f"Signed document : {signed}") print(verify_key.verify(signed).decode('utf-8')) except: print("document is altered")