def setUpClass(cls): cls.public_ip = '123.45.67.89' cls.port = 12345 cls.own_addr = (cls.public_ip, cls.port) cls.addr1 = ('132.54.76.98', 54321) cls.addr2 = ('231.76.45.89', 15243) cls.privkey1_hex = '71d1054068b224a4d9013104881dc7f46c6fec9a618f4574ae21059723e6c4f8' cls.privkey1 = public.PrivateKey(cls.privkey1_hex, encoder=encoding.HexEncoder) cls.pubkey1 = cls.privkey1.public_key cls.pubkey1_bytes = cls.pubkey1.encode(encoder=encoding.RawEncoder) cls.privkey2_hex = '4c107b7844368d0fb608f3d91ae194f2d62c7ff91b713e5b05c279e8b7fc61b3' cls.privkey2 = public.PrivateKey(cls.privkey2_hex, encoder=encoding.HexEncoder) cls.pubkey2 = cls.privkey2.public_key cls.pubkey2_bytes = cls.pubkey2.encode(encoder=encoding.RawEncoder) cls.remote_crypto_box = public.Box(cls.privkey2, cls.pubkey1) cls.nonce = utils.random(cls.remote_crypto_box.NONCE_SIZE) cls.local_crypto_box = public.Box(cls.privkey1, cls.pubkey2) cls.privkey3_hex = '40246691a4362a220606dd302b03e992b5b5fe21026377fa56c9fe3f5afbcbd0' cls.privkey3 = public.PrivateKey(cls.privkey3_hex, encoder=encoding.HexEncoder) cls.pubkey3 = cls.privkey3.public_key cls.pubkey3_bytes = cls.pubkey3.encode(encoder=encoding.RawEncoder) cls.other_crypto_box = public.Box(cls.privkey3, cls.pubkey1)
def decryptDict(dct, signingPrivateKey, realPrivateKey, realPublicKey): """decrypt all values in a dictionary Assumes all values in a dictionary are base64ed encrypted with realPublicKey, and signed with signingPrivateKey, and decrypt them with realPrivateKey. If realPrivateKey and realPublicKey do not correspond to each other, or any value in the dictionary is not signed and encrypted correctly, an exception is raised. :param dct: encrypted dictionary :type dct: dictionary with string values and keys :param signingPrivateKey: base64 encoded NaCl private key :type signingPrivateKey: string :param realPrivateKey: base64 encoded NaCl private key :type realPrivateKey: string :param realPublicKey: base64 encoded NaCl private key :type realPublicKey: string :rtype: dictionary with string values and keys """ signingPrivateKey = npublic.PrivateKey( base64.decodestring(signingPrivateKey)) signingPublicKey = signingPrivateKey.public_key realPrivateKey = npublic.PrivateKey(base64.decodestring(realPrivateKey)) realPublicKey = npublic.PublicKey(base64.decodestring(realPublicKey)) if realPrivateKey.public_key.encode() != realPublicKey.encode(): raise ValueError('private key and public key do not match', realPrivateKey.public_key, realPublicKey) box = npublic.Box(realPrivateKey, signingPublicKey) ret = {} for key, value in six.iteritems(dct): decodedValue = base64.decodestring(value) decryptedValue = box.decrypt(decodedValue) ret[key] = decryptedValue return ret
def del_(addr, fil): pkr = requests.get(addr + "/pk", verify=False) sk = pkr.json()["key"] mypub, mysec, nospam = read_tox(fil) check = _compute_checksum(mypub + nospam) print("kotone: Deleting {0} from server.".format(mypub, check)) inner = json.dumps({ "public_key": mypub, # Public key "timestamp": int(time.time()) # Timestamp }) k = crypto.PrivateKey(mysec, crypto_encode.HexEncoder) nonce = os.urandom(crypto.Box.NONCE_SIZE) b = crypto.Box(k, crypto.PublicKey(sk, crypto_encode.HexEncoder)) msg = b.encrypt(inner.encode("utf8"), nonce, crypto_encode.Base64Encoder) payload = json.dumps({ "action": 2, "public_key": mypub, "encrypted": msg.ciphertext.decode("utf8"), "nonce": crypto_encode.Base64Encoder.encode(nonce).decode("utf8") }) resp = requests.post(addr + "/api", data=payload, verify=False) a = resp.json() if a["c"] == 0: print("\033[32mOK:\033[0m record deleted. " "It may take a minute to update.") else: print("\033[32mFailed:\033[0m {0}".format(a["c"]))
def post(self, request): form = USF(request.POST) if not form.is_valid(): raise RuntimeError("Invalid HTML Form submitted") password = form.cleaned_data['password'] pseudonym = form.cleaned_data['pseudonym'] kdf = KDF( algorithm=hashes.Whirlpool(), length=int( 32 + 32), # 32: Edwards25519 seed, second 32: Curve25519 seed salt=whirlpool(pseudonym.encode()), iterations=int(1e6), backend=default_backend()) key = kdf.derive(password.encode()) edkey = signfool.SigningKey( key[0:32] ) # Use the first 32-bytes of the derived key as Edwards25519 seed cvkp = pubfool.PrivateKey( key[32:64]) # Use the second half as Curve25519 seed try: sig = db.get('gks').sign(cvkp.public_key.encode(encoder=b64)) except KeyError: return render(request, 'freakedup.html', {'err': "You are not part of a group, yet"}) db.set("user-edkeys", edkey) db.set("user-cvkeys", cvkp) db.set("user-keysig", sig) edkey_fingerprint = base64.b64encode(whirlpool( edkey._signing_key)).decode() cvkey_fingerprint = base64.b64encode(whirlpool( cvkp._private_key)).decode() ctx = dict(edkey_fp=edkey_fingerprint, cvkey_fp=cvkey_fingerprint, sig=base64.b64encode(sig).decode()) return render(request, 'user.post.html', ctx)
def get_public_key(secret_pass): # 1. hex string to bytes # 2. sha256 as bytes # 3. curve25519 keygen .p (?) # 4. byte array to hex string secret_pass_as_hex = secret_pass if not conv.is_hex(secret_pass): secret_pass_as_hex = conv.string_to_hex_string(secret_pass) b = conv.hex_string_to_bytes(secret_pass_as_hex) bh = simple_hash(b) pub = curve25519.PrivateKey(bh).public_key._public_key # as bytes return conv.bytearray_to_hex_string(pub)
def __init__(self): """Load or initialize crypto keys.""" try: with open("key", "rb") as keys_file: keys = keys_file.read() except IOError: keys = None if keys: self.pkey = public.PrivateKey(keys, STORE_ENC) else: kp = public.PrivateKey.generate() with open("key", "wb") as keys_file: keys_file.write(kp.encode(STORE_ENC)) self.pkey = kp
def __init__(self, secret_key: Optional[Union[bytes, str, List[int], int]] = None): """Create a new Account object. :pararm secret_key: Secret key for the account. """ key: Optional[bytes] = None if isinstance(secret_key, int): key = bytes(PublicKey(secret_key)) if isinstance(secret_key, list): key = bytes(secret_key) elif isinstance(secret_key, str): key = bytes(secret_key, encoding="utf-8") elif isinstance(secret_key, bytes): key = secret_key self._secret = public.PrivateKey(key) if key else public.PrivateKey.generate()
def encrypt(value, signingPrivateKey, realPublicKey): """encrypt and sign a value, and base64-encode the result :param value: a secret :type value: string :param signingPrivateKey: base64 encoded NaCl private key :type signingPrivateKey: string :param realPublicKey: base64 encoded NaCl private key :type realPublicKey: string :rtype: string """ signingPrivateKey = npublic.PrivateKey( base64.decodestring(signingPrivateKey)) realPublicKey = npublic.PublicKey(base64.decodestring(realPublicKey)) box = npublic.Box(signingPrivateKey, realPublicKey) nonce = nutils.random(npublic.Box.NONCE_SIZE) encrypted = box.encrypt(value, nonce) encoded = base64.encodestring(encrypted) oneline = ''.join(encoded.splitlines()) return oneline
def __init__(self, proto, handler, own_addr, dest_addr, relay_addr=None, private_key=None): """ Create a new connection and register it with the protocol. Args: proto: Handler to underlying protocol. handler: Upstream recipient of received messages and handler of other events. Should minimally implement `receive_message` and `handle_shutdown`. own_addr: Tuple of local host address (ip, port). dest_addr: Tuple of remote host address (ip, port). relay_addr: Tuple of relay host address (ip, port). private_key: A private key for Curve25519, as a hex-encoded public.PrivateKey. The instance will automatically generate a new such key if one is not provided. If a relay address is specified, all outgoing packets are sent to that adddress, but the packets contain the address of their final destination. This is used for routing. """ super(CryptoConnection, self).__init__(proto, handler, own_addr, dest_addr, relay_addr) if private_key is None: self._private_key = public.PrivateKey.generate() else: self._private_key = public.PrivateKey(private_key, encoder=encoding.HexEncoder) self._public_key = self._private_key.public_key self._crypto_box = None self._remote_public_key = None self._left_nonce_bytes = utils.random(public.Box.NONCE_SIZE // 2)
def __init__(self, secret_key: Optional[Union[bytes, str, List[int], int]] = None): """Create a new Account object. :pararm secret_key: Secret key for the account. """ warn( "solana.account.Account is deprecated, please use solana.keypair.KeyPair", category=DeprecationWarning) key: Optional[bytes] = None if isinstance(secret_key, int): key = bytes(PublicKey(secret_key)) if isinstance(secret_key, list): key = bytes(secret_key) elif isinstance(secret_key, str): key = bytes(secret_key, encoding="utf-8") elif isinstance(secret_key, bytes): key = secret_key self._secret = public.PrivateKey( key) if key else public.PrivateKey.generate()
def decrypt_key(private_key): password = getpass.getpass() with open(private_key, 'r') as in_file: salt = in_file.read(16) in_file.seek(16) encrypted = in_file.read(72) in_file.seek(88) mem = int(in_file.read()) key = kdf(secret.SecretBox.KEY_SIZE, password, salt, opslimit=ops, memlimit=mem) box = secret.SecretBox(key) loaded_private_key = box.decrypt(encrypted) loaded_private_key = public.PrivateKey(loaded_private_key, encoder=encoding.RawEncoder) return loaded_private_key
def push(addr, name, bio, fil): pkr = requests.get(addr + "/pk", verify=False) sk = pkr.json()["key"] mypub, mysec, nospam = read_tox(fil) check = _compute_checksum(mypub + nospam) print("kotone: Publishing {0}/{1} to server.".format(mypub, check)) inner = json.dumps({ "tox_id": mypub + nospam + check, # Public key + checksum "name": name, # Desired name "privacy": 1, # Privacy level (1 or higher appears in FindFriends) "bio": bio.strip(), # Bio (quote displayed on web) "timestamp": int(time.time()) # A timestamp near the server's time }) k = crypto.PrivateKey(mysec, crypto_encode.HexEncoder) nonce = os.urandom(crypto.Box.NONCE_SIZE) b = crypto.Box(k, crypto.PublicKey(sk, crypto_encode.HexEncoder)) msg = b.encrypt(inner.encode("utf8"), nonce, crypto_encode.Base64Encoder) payload = json.dumps({ "action": 1, # Action number "public_key": mypub, # Public key "encrypted": msg.ciphertext.decode("utf8"), # Encrypted payload base64 (above) "nonce": crypto_encode.Base64Encoder.encode(nonce).decode("utf8") # b64 }) resp = requests.post(addr + "/api", data=payload, verify=False) a = resp.json() if a["c"] == 0: print("\033[32mOK:\033[0m record successfully published.") print("Password is '{0}'.".format(a["password"])) else: print("\033[32mFailed:\033[0m {0}".format(a["c"]))
def post(self, request): form = GSF(request.POST) pubk = None privk = None pubfp = None privfp = None edseed = None if not form.is_valid(): raise RuntimeError("Invalid HTML form submitted") seed = form.cleaned_data['seed'] if seed == 'none': gke = pubfool.PrivateKey.generate() gks = signfool.SigningKey.generate() db.set('gke', gke) db.set('gks', gks) seed = base64.b64encode( json.dumps( dict(gke={ 'public_key': base64.b64encode(gke.public_key._public_key).decode(), 'private_key': base64.b64encode(gke._private_key).decode() }, gks={'seed': base64.b64encode(gks._seed).decode() })).encode()).decode() pubk = gke.public_key._public_key privk = gke._private_key edseed = gks._seed sk = gks.verify_key.encode(encoder=b64) ek = gke.public_key.encode(encoder=b64) gkfp = base64.b64encode(whirlpool(sk + ek)) db.set('gkfp', gkfp.decode()) sendgroup(gkfp, sk, ek) else: seed = base64.b64decode(seed).decode() seed = json.loads(seed) # Format of seed: # {'public_key': 'base64-encoded PublicKey', 'private_key': 'base64-encoded PrivateKey'} pub = pubk = base64.b64decode(seed['gke']['public_key']) if len(pub) != 32: return "Error: Public key's length should be 32 bytes, check your input" priv = privk = base64.b64decode(seed['gke']['private_key']) if len(priv) != 32: return "Error: Private key's length should be 32 bytes, check your input tool" # Construct a PublicKey object pub = pubfool.PublicKey(pub) # Construct a Private Key object priv = pubfool.PrivateKey(priv) priv.public_key = pub edseed = base64.b64decode(seed['gks']['seed']) gks = signfool.SigningKey(seed=edseed) sk = gks.verify_key.encode(encoder=b64) ek = priv.public_key.encode(encoder=b64) gkfp = base64.b64encode(whirlpool(sk + ek)) # Save the key db.set('gke', priv) db.set('gks', gks) db.set('gkfp', gkfp.decode()) # I think it's already sent to the server because it was off a seed # Create a seed pubfp = base64.b64encode(whirlpool(pubk)).decode() privfp = base64.b64encode(whirlpool(privk)).decode() edseed = base64.b64encode(whirlpool(edseed)).decode() return render(request, 'group.post.html', { 'edseed': edseed, 'pubfp': pubfp, 'privfp': privfp, 'seed': seed, })
def curve25519_pub_from_seed(seed): return curve25519.PrivateKey(seed).public_key