Skip to content

Go io.Reader Decrypt Example #796

@jacobmiller22

Description

@jacobmiller22

Hi there! Can there be an example of using the golang esdk to decrypt from a readable stream via an io.Reader?

I'm working on an example where the ciphertext is created with AWS Encryption SDK using a multiregion key and RequireEncryptAllowDecrypt commitment policy. Using a modified version of the awskmsmrkkeyring example, I can decrypt the entire file if I load it all into memory.

I'm not sure if the std lib way to do it is to use cipher.StreamReader? Particularly, I just don't know what to use for the nonce, key, and whether or not it is using GCM or some other block mode, or how to connect that to the esdk client

Thank you for any help!

Creating the encrypted file with this script:

import argparse
import sys

import aws_encryption_sdk as aes

def main(infile, outfile):
  client = aes.EncryptionSDKClient(
      commitment_policy=aes.CommitmentPolicy.REQUIRE_ENCRYPT_ALLOW_DECRYPT,
  )
  key_provider = aes.StrickAwsKmsMasterKeyProvider(
    key_ids=[
      __myKeyArn__
    ],
  )
  with client.stream(mode="e", source=infile, key_provider=key_provider) as encryptor:
    for chunk in encryptor:
      outfile.write(chunk)

if __name__ == "__main__":
  parser = argparse.ArgumentParser(description="Encrypt a file")
  parser.add_argument("--input", type=argparse.FileType("rb"), help="File to encrypt", default=sys.stdin, required=False)
  parser.add_argument("--output", type=argparse.FileType("wb"), help="Encrypted output file", required=True)
  args = parser.parse_args()
  main(args.input, args.output)

Edit: My attempt to decrypt chunk by chunk was along these lines, got a Incomplete message: ReadFramedMessageBody :

func(input io.Reader, output io.Reader) {
  // For brevity not doing any error handling
  buffer := make([]byte, 4096) // 4096 byte frames

  var n int
  var err error
  for {
    n, err = input.Read(buffer)
    
    if n <= 0 {
        break
    }

    decryptResp, err := encryptionClient.Decrypt(context.TODO(), esdktypes.DecryptInput{
        Keyring: keyring, // Created using the mrk example
        Ciphertext: buffer[:n]
    })
    
    //  handle err
     
    output.Write(decryptResp.Plaintext)
  }

// ...
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions