示例#1
0
def index(file_id):

    # Locate document. This sample should not continue if the file is not found.
    if not exists(join(current_app.config['APPDATA_FOLDER'], file_id)):
        return render_template('error.html', msg='File not found')

    # Get an instance of the PadesTimestamper class, used to timestamp a PDF
    # file.
    stamper = PadesTimestamper()

    # Set PKI default (see utils.py).
    set_pki_defaults(stamper)

    # Set the PDF to be timestamped.
    stamper.set_pdf_from_path(join(current_app.config['APPDATA_FOLDER'],
                                   file_id))

    # Generate path for output file and add to the stamper.
    create_app_data()  # Guarantees that "app_data" folder exists.
    output_file = '%s.pdf' % str(uuid.uuid4())
    output_file_path = join(current_app.config['APPDATA_FOLDER'], output_file)
    stamper.output_file_path = output_file_path

    # Add a timestamp to the PDF file.
    stamper.stamp()

    # Return the stamped PDF as a downloadable file.
    return send_from_directory(current_app.config['APPDATA_FOLDER'],
                               output_file)
示例#2
0
def upload(rc):
    """

    This function allows the user to upload a file to be signed. Once the file
    is uploaded, we save it to the app_data folder and redirect the user to
    cades-signature or pades-signature view passing the filename on the
    "userfile" URL argument.

    """

    if request.method == 'POST':
        userfile = request.files['userfile']

        # Generate a unique filename.
        filename = '%s_%s' % (str(uuid.uuid4()), secure_filename(
            userfile.filename))

        # Move the file to the "app_data" with the unique filename. Make sure
        # the "app_data" folder exists (static/util.py).
        create_app_data()
        userfile.save(
            os.path.join(current_app.config['APPDATA_FOLDER'], filename))

        # Redirect the user to the redirect parameter "rc".
        if request.args.get('certId', None) is not None:
            return redirect('/%s/%s?certId=%s' % (rc, filename, request.args.get('certId')))
        return redirect('/%s/%s' % (rc, filename))
    else:
        return render_template('upload/index.html')
示例#3
0
def action():
    # Get the token for this signature. (rendered in a hidden input field, see
    # xml-signature/index.html template)
    token = request.form['token']

    # Instantiate the XmlSignatureFinisher class, responsible for completing
    # the signature process.
    signature_finisher = XmlSignatureFinisher(get_rest_pki_client())

    # Set the token.
    signature_finisher.token = token

    # Call the finish() method, which finalizes the signature process and
    # returns the signed XML.
    result = signature_finisher.finish()

    # Get information about the certificate used by the user to sign the file.
    # This method must only be called after calling the finish() method.
    signer_cert = result.certificate

    # At this point, you'd typically store the signed PDF on your database. For
    # demonstration purposes, we'll store the XML on a temporary folder publicly
    # accessible and render a link to it.

    create_app_data()  # Guarantees that "app data" folder exists.
    filename = '%s.xml' % (str(uuid.uuid4()))
    result.write_to_file(join(current_app.config['APPDATA_FOLDER'], filename))

    return render_template('xml_signature_rest/complete.html',
                           signed_xml=filename,
                           signer_cert=signer_cert)
示例#4
0
def complete(token=None):
    """

    This function is called asynchornously via AJAX by the batch signature page
    for each document being signed. It receives the tokne, that identifies the
    signature process. We'll call REST PKI to complete this signature and return
    a JSON with the saved filename so that the page can render a link to it.

    """

    # Get an intance of the PadesSignatureFinisher class, responsible for
    # completing the signature process.
    signature_finisher = PadesSignatureFinisher(get_restpki_client())

    # Set the token.
    signature_finisher.token = token

    # Call the finish() method, which finalizes the signature process.The
    # return value is the signed PDF content.
    result = signature_finisher.finish()

    # At this point, you'd typically store the signed PDF on your database.
    # For demonstration purposes, we'll store the PDF on a temporary folder
    # publicly accessible and render a link to it.

    create_app_data()  # Guarantees that "app data" folder exists.
    filename = '%s.pdf' % (str(uuid.uuid4()))
    result.write_to_file(
        os.path.join(current_app.config['APPDATA_FOLDER'], filename))

    return jsonify(filename)
示例#5
0
def complete():
    # Recover variables from the POST arguments to be used on this step.
    file_id = request.form['id']
    transfer_file = request.form['transferFile']
    signature = request.form['signature']

    # Get an instance of the SignatureFinisher class, responsible for completing
    # the signature process.
    signature_finisher = SignatureFinisher()

    # Set PKI default options (see utils.py).
    set_pki_defaults(signature_finisher)

    # Set the file to be signed. It's the same file we use don "start" method.
    signature_finisher.set_file_to_sign_from_path(
        get_sample_batch_doc_path(file_id))

    # Set the transfer file.
    signature_finisher.set_transfer_file_from_path(transfer_file)

    # Set the signature file.
    signature_finisher.signature = signature

    # Generate path for output file and add to the signature finisher.
    create_app_data()  # Guarantees that "app data" folder exists.
    filename = '%s.p7s' % (str(uuid.uuid4()))
    signature_finisher.output_file = \
        join(current_app.config['APPDATA_FOLDER'], filename)

    # Complete the signature process.
    signature_finisher.complete()

    return jsonify(filename)
示例#6
0
def attached(file_id1, file_id2):
    """

    This function performs a merge of CAdES signature using PKI Express
    when both signatures have encapsulated content

    """
    # Get an instance of the CadesSignatureEditor class, responsible for
    # receiving the files and merge them.
    signature_editor = CadesSignatureEditor()

    # Set PKI default options (see utils.py).
    set_pki_defaults(signature_editor)

    # Guarantees that "app data" folder exists.
    create_app_data()

    # Generate output filename
    output_file = '%s.p7s' % (str(uuid.uuid4()))

    # Add both signatures
    signature_editor.add_cms_file_from_path(
        os.path.join(current_app.config['APPDATA_FOLDER'], file_id1))
    signature_editor.add_cms_file_from_path(
        os.path.join(current_app.config['APPDATA_FOLDER'], file_id2))

    # Set path to output file
    signature_editor.output_file = os.path.join(
        current_app.config['APPDATA_FOLDER'], output_file)

    # Merge files
    signature_editor.merge()
    return render_template('merge_cades_express/index.html',
                           output_file=output_file)
示例#7
0
def index(rc, op):
    if request.method == 'GET':
        if op == "cosignCms":
            available_files = [
                ServerFileModel(SampleDocs.CMS_SIGNED_ONCE,
                                "A sample CMS file that was signed once."),
                ServerFileModel(SampleDocs.CMS_SIGNED_TWICE,
                                "A sample CMS file that was signed twice.")
            ]
        elif op == "cosignPdf" or op == "printerFriendlyPdf":
            available_files = [
                ServerFileModel(SampleDocs.PDF_SIGNED_ONCE,
                                "A sample PDF that was signed once."),
                ServerFileModel(SampleDocs.PDF_SIGNED_TWICE,
                                "A sample PDF that was signed twice.")
            ]
        elif op == "signCms" or op == "signPdf":
            available_files = [
                ServerFileModel(SampleDocs.SAMPLE_PDF,
                                "A sample PDF file to be signed.")
            ]
        else:
            return render_template('error.html', msg='Invalid Operation')

        return render_template('server_files/index.html',
                               rc=rc,
                               available_files=available_files)
    else:
        sample_id = int(request.form['selectedFile'])
        filename = get_sample_doc_name(sample_id)
        file_extension = filename.rsplit('.', 1)[1]

        # Copy file to the App_Data folder, where the upload files is stored.
        with open(os.path.join(current_app.static_folder, filename),
                  'rb') as f:
            sample_file = f.read()
        # Generate a unique filename.
        file_id = '%s.%s' % (str(uuid.uuid4()), file_extension)

        # Move the file to the "app_data" with the unique filename. Make sure
        # the "app_data" folder exists (static/util.py).
        create_app_data()
        with open(os.path.join(current_app.config['APPDATA_FOLDER'], file_id),
                  'wb') as f:
            f.write(sample_file)

        # Redirect the user to the signature route, passing the name of the file as
        # a URL argument.
        redirect_url = rc
        if op == "cosignCms":
            redirect_url += '/cosign/' + file_id
        else:
            redirect_url += '/' + file_id

        return redirect(redirect_url)
def index(file_id):

    # Verify if the provided "file_id" exists.
    file_path = join(current_app.config['APPDATA_FOLDER'], file_id)
    if not exists(file_path):
        return render_template('error.html', msg='File not found')

    # Get an instance of the PadesSigner class, responsible for receiving
    # the signature elements and performing the local signature.
    signer = PadesSigner()

    # Set PKI default options (see utils.py).
    set_pki_defaults(signer)

    # Set signature policy.
    signer.signature_policy = standard_signature_policies.PADES_BASIC_WITH_LTV

    # Set PDF to be signed.
    signer.set_pdf_to_sign_from_path(file_path)

    # The PKCS #12 certificate path.
    signer.set_pkcs12_from_path(
        join(current_app.static_folder, 'Pierre de Fermat.pfx'))
    # Set the certificate's PIN.
    signer.cert_password = '******'

    # Set a file reference for the stamp file. Note that this file can be
    # referenced later by "fref://{alias}" at the "url" field on the visual
    # representation (see content/vr.json or get_visual_representation()
    # method).
    signer.add_file_reference('stamp', get_pdf_stamp_path())

    # Set visual representation. We provide a dictionary that represents the
    # visual representation JSON model.
    signer.set_visual_representation(
        PadesVisualElementsExpress.get_visual_representation())

    # Generate path for output file and add to signer object.
    create_app_data()  # Guarantees that "app data" folder exists.
    output_file = '%s.pdf' % (str(uuid.uuid4()))
    signer.output_file = join(current_app.config['APPDATA_FOLDER'],
                              output_file)

    # Perform the signature.
    signer_cert = signer.sign(get_cert=True)

    response = make_response(
        render_template('pades_server_key_express/index.html',
                        signer_cert=signer_cert,
                        signed_pdf=output_file))
    get_expired_page_headers(response.headers)

    return response
def copy_from_static_to_app_data(filename):
    # Copy file to the App_Data folder, where the upload files is stored.
    with open(os.path.join(current_app.static_folder, filename), 'rb') as f:
        sample_file = f.read()
    # Generate a unique filename.
    new_filename = '%s.%s' % (str(uuid.uuid4()), 'p7s')

    # Move the file to the "app_data" with the unique filename. Make sure
    # the "app_data" folder exists (static/util.py).
    create_app_data()
    with open(os.path.join(current_app.config['APPDATA_FOLDER'], new_filename),
              'wb') as f:
        f.write(sample_file)

    return new_filename
示例#10
0
def complete(file_id):
    """

    This function completes the signature, it will be called programatically
    after the Web PKI component perform the signature and submit the form (see
    method sign() on static/js/signature-complete-form.js).

    """
    try:

        # Recover variables from the POST arguments to be used on this step.
        transfer_file_id = request.form['transferFileIdField']
        signature = request.form['signatureField']

        # Get an instance of the SignatureFinisher class, responsible for
        # completing the signature process.
        signature_finisher = SignatureFinisher()

        # Set PKI default options (see utils.py).
        set_pki_defaults(signature_finisher)

        # Set the file to be signed. It's the same file we used on "start"
        # method.
        signature_finisher.set_file_to_sign_from_path(
            os.path.join(current_app.config['APPDATA_FOLDER'], file_id))

        # Set the transfer file.
        signature_finisher.set_transfer_file_from_path(transfer_file_id)

        # Set the signature file.
        signature_finisher.signature = signature

        # Generate path for output file and add to the signature finisher.
        create_app_data()  # Guarantees that "app data" folder exists.
        output_file = '%s.p7s' % (str(uuid.uuid4()))
        signature_finisher.output_file = \
            os.path.join(current_app.config['APPDATA_FOLDER'], output_file)

        # Complete the signature process.
        signer_cert = signature_finisher.complete(get_cert=True)

        return render_template('cades_signature_express/signature-info.html',
                               signer_cert=signer_cert,
                               cms_file=output_file)

    except Exception as e:
        return render_template('error.html', msg=e)
示例#11
0
def index(file_id=None):
    # Verify if the provided "file_id" exists.
    file_path = join(current_app.config['APPDATA_FOLDER'], file_id)
    if not exists(file_path):
        return render_template('error.html', msg='File not found')

    # Get an instance of the CadesSigner class, responsible for receiving
    # the signature elements and performing the local signature.
    signer = CadesSigner()

    # Set PKI default options (see utils.py).
    set_pki_defaults(signer)

    # Set signature policy.
    signer.signature_policy = \
        standard_signature_policies.PKI_BRAZIL_CADES_ADR_BASICA

    # Set file to be signed. If the file is a CSM, the PKI Express will
    # recognize that and will co-sign that file.
    signer.set_file_to_sign_from_path(file_path)

    # The PKCS #12 certificate path.
    signer.set_pkcs12_from_path(
        join(current_app.static_folder, 'Pierre de Fermat.pfx'))
    # Set the certificate's PIN.
    signer.cert_password = '******'

    # Set 'encapsulate content' option (default: True).
    signer.encapsulated_content = True

    # Generate path for output file and add to signer object.
    create_app_data()  # Guarantees that "app_data" folder exists.
    output_file = '%s.p7s' % (str(uuid.uuid4()))
    signer.output_file = join(current_app.config['APPDATA_FOLDER'],
                              output_file)

    # Perform the signature.
    signer_cert = signer.sign(get_cert=True)

    response = make_response(
        render_template('cades_server_key_express/index.html',
                        signer_cert=signer_cert,
                        cms_file=output_file))
    get_expired_page_headers(response.headers)

    return response
def action():
    """

    This function receives the form submission from the template
    cades-signature/index.html. We'll call REST PKI to complete the signature.

    """

    try:

        # Get the token for this signature. (rendered in a hidden input field,
        # see pades-signature/index.html template)
        token = request.form['token']

        # Get an intance of the PadesSignatureFinisher class, responsible for
        # completing the signature process.
        signature_finisher = PadesSignatureFinisher(get_rest_pki_client())

        # Set the token.
        signature_finisher.token = token

        # Call the finish() method, which finalizes the signature process. The
        # return value is the signed PDF content.
        result = signature_finisher.finish()

        # Get information about the certificate used by the user to sign the
        # file. This method must only be called after calling the finish()
        # method.
        signer_cert = result.certificate

        # At this point, you'd typically store the signed PDF on your database.
        # For demonstration purposes, we'll store the PDF on a temporary folder
        # publicly accessible and render a link to it.

        create_app_data()  # Guarantees that "app data" folder exists.
        filename = '%s.pdf' % (str(uuid.uuid4()))
        result.write_to_file(
            os.path.join(current_app.config['APPDATA_FOLDER'], filename))

        return render_template('pades_signature_rest/complete.html',
                               signer_cert=signer_cert,
                               signed_pdf=filename)

    except Exception as e:
        return render_template('error.html', msg=e)
示例#13
0
def complete():
    """

    This method is called asynchronously via AJAX by the batch signature page
    for each document being signed. We'll cal PKI Express to complete this
    signature and return a JSOn with the save filename so that the page a link
    to it.

    """

    # Recover variables from the POST arguments to be used on this step.
    file_id = request.form['id']
    transfer_file = request.form['transferFile']
    signature = request.form['signature']

    # Get an instance of the SignatureFinisher class, responsible for completing
    # the signature process.
    signature_finisher = SignatureFinisher()

    # Set PKI default options (see utils.py).
    set_pki_defaults(signature_finisher)

    # Set PDF to be signed. It's the same file we used on "start" method.
    signature_finisher.set_file_to_sign_from_path(
        get_sample_batch_doc_path(file_id))

    # Set the transfer file.
    signature_finisher.set_transfer_file_from_path(transfer_file)

    # Set the signature file.
    signature_finisher.signature = signature

    # Generate path for output file and add to the signature finisher.
    create_app_data()  # Guarantees that "app data" folder exists.
    filename = '%s.pdf' % (str(uuid.uuid4()))
    signature_finisher.output_file = \
        os.path.join(current_app.config['APPDATA_FOLDER'], filename)

    # Complete the signature process.
    signature_finisher.complete()

    return jsonify(filename)
示例#14
0
def complete(token):
    # Get an instance of the CadesSignatureFinisher class, responsible for
    # completing the signature process.
    signature_finisher = CadesSignatureFinisher(get_rest_pki_client())

    # Set the token.
    signature_finisher.token = token

    # Call the finish() method, which finalizes the signature process.The
    # return value is the CMS content.
    result = signature_finisher.finish()

    # At this point, you'd typically store the signed PDF on your database.
    # For demonstration purposes, we'll store the CMS on a temporary folder
    # publicly accessible and render a link to it.

    create_app_data()  # Guarantees that "app data" folder exists.
    filename = '%s.p7s' % (str(uuid.uuid4()))
    result.write_to_file(join(current_app.config['APPDATA_FOLDER'], filename))

    return jsonify(filename)
def complete():
    """

    This action will complete the authentication process and create a signature using a session
    token returned by user. Also, we recover the parameter "customState" containing the id of the
    file that will be signed.

    """
    try:
        # Recover variables from query parameters.
        code = request.args.get('code')
        state = request.args.get('state')

        # Get an instance of the TrustServiceManager class, responsible for communicating with 
        # PSCs and handling the OAuth flow.
        manager = TrustServicesManager()

        # Complete the authentication process, recovering the session info to be used on the
        # signature and the custom state (fileId).
        result = manager.complete_auth(code, state)

        # Recover file id on custom state parameter.
        file_id = result.custom_state

        # Verify if the provided file_id exists.
        file_path = join(current_app.config['APPDATA_FOLDER'], file_id)
        if not exists(file_path):
            return render_template('error.html', msg='File not found')

        # Get an instance of the PadesSigner class, responsible for receiving
        # the signature elements and performing the local signature.
        signer = PadesSigner()

        # Set PKI default options (see utils.py).
        set_pki_defaults(signer)

        # Set signature policy.
        signer.signature_policy = standard_signature_policies.PADES_BASIC_WITH_LTV

        # Set PDF to be signed.
        signer.set_pdf_to_sign_from_path(file_path)

        # Set trust session acquired on the following steps of this sample.
        signer.trust_service_session = result.session

        # Set a file reference for the stamp file. Note that this file can be
        # referenced later by "fref://{alias}" at the "url" field on the visual
        # representation (see content/vr.json or get_visual_representation()
        # method).
        signer.add_file_reference('stamp', get_pdf_stamp_path())

        # Set visual representation. We provide a dictionary that represents the
        # visual representation JSON model.
        signer.set_visual_representation(
            PadesVisualElementsExpress.get_visual_representation())

        # Generate path for output file and add to signer object.
        create_app_data()  # Guarantees that "app data" folder exists.
        output_file = '%s.pdf' % (str(uuid.uuid4()))
        signer.output_file = join(current_app.config['APPDATA_FOLDER'], output_file)

        # Perform the signature.
        signer_cert = signer.sign(get_cert=False)

        response = make_response(render_template(
            'pades_cloud_oauth_express/signature-info.html',
            signed_pdf=output_file))
        get_expired_page_headers(response.headers)

        return response

    except Exception as e:
        return render_template('error.html', msg=e)
示例#16
0
def authorize(file_id):
    """"

    This action is called after the form after the user press the button "Sign". 
    This action will receive the user's CPF and current password.

    """
    try:
        # Recover variables from the POST arguments.
        cpf = request.form['cpf']
        service = request.form['service']
        password = request.form['password']

        # Process cpf, removing all formatting.
        plainCpf = cpf.replace(".", "").replace("-", "")

        # Get an instance of the TrustServiceManager class, responsible for communicating with 
        # PSCs and handling the password flow.
        manager = TrustServicesManager()

        # Complete authentication using CPF and current password. The following method has three sessionTypes:
        # - SINGLE_SIGNATURE: The returned token can only be used for one single signature request.
        # - MULTI_SIGNATURE: The returned token can only be used for one multi signature request.
        # - SIGNATURE_SESSION: The return token can only be used for one or more signature requests.
        result = manager.password_authorize(service, plainCpf, password, trust_service_session_types.SIGNATURE_SESSION)

        # Verify if the provided file_id exists.
        file_path = join(current_app.config['APPDATA_FOLDER'], file_id)
        if not exists(file_path):
            return render_template('error.html', msg='File not found')
        
        # Get an instance of the PadesSigner class, responsible for receiving
        # the signature elements and performing the local signature.
        signer = PadesSigner()

        # Set PKI default options (see utils.py).
        set_pki_defaults(signer)

        # Set signature policy.
        signer.signature_policy = standard_signature_policies.PADES_BASIC_WITH_LTV

        # Set PDF to be signed.
        signer.set_pdf_to_sign_from_path(file_path)

        # Set trust session acquired on the following steps of this sample.
        signer.trust_service_session = result.session

        # Set a file reference for the stamp file. Note that this file can be
        # referenced later by "fref://{alias}" at the "url" field on the visual
        # representation (see content/vr.json or get_visual_representation()
        # method).
        signer.add_file_reference('stamp', get_pdf_stamp_path())

        # Set visual representation. We provide a dictionary that represents the
        # visual representation JSON model.
        signer.set_visual_representation(
            PadesVisualElementsExpress.get_visual_representation())

        # Generate path for output file and add to signer object.
        create_app_data()  # Guarantees that "app data" folder exists.
        output_file = '%s.pdf' % (str(uuid.uuid4()))
        signer.output_file = join(current_app.config['APPDATA_FOLDER'], output_file)

        # Perform the signature.
        signer_cert = signer.sign(get_cert=False)

        response = make_response(render_template(
            'pades_cloud_pwd_express/signature-info.html',
            signed_pdf=output_file))
        get_expired_page_headers(response.headers)

        return response

    except Exception as e:
        return render_template('error.html', msg=e)