goimport os, sys import base64, string import json, requests from pyasn1.codec.der.decoder import decode from pyasn1.codec.der.encoder import encode from pyasn1_modules import rfc2315 from argparse import ArgumentParser from requests.auth import HTTPBasicAuth def envelop(binFile, pkcs7String, outFile): with open(binFile,'rb') as f: encryptedBinary = f.read() f.closed # remove the -----BEGIN PKCS7----- header/footer j = pkcs7String[pkcs7String.find('\n')+1:pkcs7String.rfind('\n')] j = "".join(j) base64_img_bytes = j.encode('utf-8') env_der = base64.decodebytes(base64_img_bytes) # merge files and then compare content, rest = decode(env_der, asn1Spec=rfc2315.ContentInfo()) assert content['contentType'] == rfc2315.envelopedData myenvelope, rest = decode(content['content'], asn1Spec=rfc2315.EnvelopedData()) encr = rfc2315.EncryptedContentInfo() encr['contentType'] = myenvelope['encryptedContentInfo']['contentType'] encr['contentEncryptionAlgorithm'] = myenvelope['encryptedContentInfo']['contentEncryptionAlgorithm'] encr['encryptedContent'] = memoryview(encryptedBinary) myenvelope['encryptedContentInfo'] = encr newcontent = rfc2315.ContentInfo() newcontent['contentType'] = rfc2315.envelopedData newcontent['content'] = encode(myenvelope) envelope_buffer = memoryview(encode(newcontent)) with open(outFile,'wb') as f: f.write(envelope_buffer) f.closed if __name__ == "__main__": parser = ArgumentParser(description='This script is used to create a digital envelope from the raw recording. Example: python envelop-pkcs7.py -binFile abc00000001.mp3.bin -output abc00000001.mp3.bin.pkcs7') parser.add_argument("-binFile", action='store', dest="binFile", type=str, required=True, help='File path to the bin file downloaded') parser.add_argument("-jsonFile", action='store', dest="jsonFile", type=str, required=True, help='File path to the json file downloaded') parser.add_argument("-output", action='store', dest="outFile", type=str, required=True, help='File path to save the digital envelope bin file') args = parser.parse_args() pkcs7String = "" try: with open(args.jsonFile) as f: data = json.load(f) pkcs7String = data['mediaFiles'][0]["pkcs7"] print(pkcs7String) except: print("Reading PKCS7 failed") sys.exit() if pkcs7String: envelop(args.binFile, pkcs7String, args.outFile) print("Done!") else: print("PKCS7 key not found in JSON file.")