from tweetnacl.raw import randombytes, crypto_secretbox, crypto_secretbox_open, crypto_secretbox_KEYBYTES, crypto_secretbox_NONCEBYTES import base64 import sys # Encrypt and decrypt using tweetnacl secret box: # - 256 bit key, urlsafe_base64 encoded # - 256 bit authenticator # - random 192 bit nonce # - cyphertext is returned urlsafe_base64 encoded # - standard and compatible # - relatively new and progressive # - very fast, very simple, fairly compact def gen_key(): key = randombytes(crypto_secretbox_KEYBYTES) key_b64 = base64.urlsafe_b64encode(key) return key_b64 def encrypt(plaintext, key_b64): key = base64.urlsafe_b64decode(key_b64.upper()) nonce = randombytes(crypto_secretbox_NONCEBYTES) encrypted = crypto_secretbox(plaintext, nonce, key) ciphertext = nonce + encrypted ciphertext_b64 = base64.urlsafe_b64encode(ciphertext) return ciphertext_b64 def decrypt(ciphertext_b64, key_b64): ciphertext = base64.urlsafe_b64decode(ciphertext_b64) key = base64.urlsafe_b64decode(key_b64.upper()) nonce = ciphertext[0:crypto_secretbox_NONCEBYTES] encrypted = ciphertext[crypto_secretbox_NONCEBYTES:] plaintext = crypto_secretbox_open(encrypted, nonce, key) return plaintext def test(n=2): crypto = sys.modules[__name__] key = crypto.gen_key() print "key", key text = "hello \0 world, this is a little crypto test\0" print "text, len", repr(text), len(text) for i in range(0, int(n)): enc = crypto.encrypt(text, key) print "encrypted", enc dec = crypto.decrypt(enc, key) assert dec == text, "crypto.test" print "decrypted OK" if __name__ == "__main__": op = sys.argv[1] print globals()[op](*sys.argv[2:])