Encryption Keys
Working with encryption keys
Larky code sample
load("@stdlib//base64", base64="base64")
load("@stdlib//json", json="json")
load("@stdlib//larky", larky="larky")
load("@stdlib//builtins", builtins="builtins")
load("@vgs//vault", "vault")
load("@vendor//Crypto/Cipher/PKCS1_OAEP", PKCS1_OAEP="PKCS1_OAEP")
load("@vendor//Crypto/PublicKey/RSA", RSA="RSA")
def process(input, ctx):
# reading body
body = json.loads(str(input.body))
# reading headers
headers = input.headers
# careful reading:
# if header is absent - use hardcoded alias
# if header exists - read it and delete
private_key = 'tok_sandbox_wptPRsWr2N5hyXGvkZ8247'
if 'private' in headers:
private_key = headers.pop('private')
public_key = 'tok_sandbox_8uLH3XdekgzSYa2mpiRwwi'
if 'public' in headers:
public_key = headers.pop('public')
# reveal of keys
private_key = vault.reveal(private_key)
public_key = vault.reveal(public_key)
## Encryption part:
message = bytes(body['message'], 'utf-8')
# importing public key
key = RSA.importKey(base64.b64decode(public_key))
# encrypt
cipher = PKCS1_OAEP.new(key)
ciphertext = cipher.encrypt(message)
# writing result into the body
body['message_encrypted'] = base64.b64encode(ciphertext).decode('utf-8')
## Decryption part:
body_utf8 = base64.b64decode(bytes(body['message_encrypted'], 'utf-8'))
# importing private key
key = RSA.importKey(base64.b64decode(private_key))
# decrypt
cipher = PKCS1_OAEP.new(key)
message = cipher.decrypt(body_utf8)
# writing result into the body
body['message_decrypted'] = str(message)
input.body = builtins.bytes(json.dumps(body))
input.headers = headers
return inputTesting (with headers)
Testing (without headers)
Preparing encryption keys
Useful links
Last updated

