Add methods encrypt_bulk, decrypt_bulk, and derive_path_key

pull/42/head
tuxxy 2017-09-20 11:23:44 -07:00
parent b848da27ea
commit 939371b700
1 changed files with 43 additions and 0 deletions

View File

@ -1,6 +1,8 @@
import sha3
from nacl.utils import random
from nkms.crypto.keypairs import SigningKeypair, EncryptingKeypair
from nkms.crypto import (default_algorithm, pre_from_algorithm,
symmetric_from_algorithm)
class KeyRing(object):
@ -15,6 +17,8 @@ class KeyRing(object):
"""
self.sig_keypair = SigningKeypair(sig_privkey)
self.enc_keypair = EncryptingKeypair(enc_privkey)
self.pre = pre_from_algorithm(default_algorithm)
self.symm = symmetric_from_algorithm(default_algorithm)
@property
def sig_pubkey(self):
@ -96,3 +100,42 @@ class KeyRing(object):
:return: Secure random generated bytestring of <length> bytes
"""
return random(length)
def derive_path_key(self, path, is_pub=True):
"""
Derives a key for the specific path.
:param bytes path: Path to generate the key for
:param bool is_pub: Is the derived key a public key?
:rtype: bytes
:return: Derived key
"""
key = sha3.keccak_256(self.enc_privkey + path).digest()
return self.pre.priv2pub(key) if is_pub else key
def encrypt_bulk(self, data, key):
"""
Encrypt bulk of the data with nacl's SecretBox.
:param bytes data: Data to encrypt
:param bytes key: Symmetric key
:rtype: bytes
:return: Ciphertext of encrypted data
"""
cipher = self.symm(key)
return cipher.encrypt(data)
def decrypt_bulk(self, ciphertext, key):
"""
Decrypts bulk of the data with nacl's SecretBox.
:param bytes ciphertext: Ciphertext to decrypt
:param bytes key: Symmetric key
:rtype: bytes
:return: Plaintext decrypted from ciphertext
"""
cipher = self.symm(key)
return cipher.decrypt(ciphertext)