SignEncrypt operations samples

This sample code page demonstrates how to use SignEncrypt operations such as signature and verification using high level SCWS entry points. It also provides examples about how to manipulate JavaScript Blobs which are used by these entry points.

JavaScript Blobs code samples

Get a Blob from a local file

<div id="filediv">
        <label for="input">Input Blob</label>
        <input id="input" type="file">
</div>
/* Get PDF from local storage as a Blob */
function getBlobFromLocal(inputID) {
        var selectedFile = document.getElementById(inputID).files[0];
        return selectedFile;
}

Note: getElementById returns a File object here, which is itself a Blob object.

Get a Blob from a remote file on a web server

/* Get file from server running locally on 127.0.0.1:1234, then create a blob from it */
function getBlobFromServer() {
return new Promise(function(resolve, reject) {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', 'http://127.0.0.1:1234/example_test.pdf', true);
        xhr.responseType = 'blob';
        xhr.onload = function(e) {
                if (this.status == 200) {
                        resolve(this.response);
                }
        };
        xhr.send();
});
}

Save a file on local disk from a Blob

/* Download file content from a blob */
function downloadBlobLocal(blob, fileName) {
        var a = document.createElement("a");
        document.body.appendChild(a);
        a.style = "display: none";
        var url = window.URL.createObjectURL(blob);
        a.href = url;
        a.download = fileName;
        a.click();
        window.URL.revokeObjectURL(url);
};

Save a file on local disk from a Blob

/* Send a Blob object to web server running locally on 127.0.0.1:1234 */
function sendBlobToServer(blob) {
        var xhr = new XMLHttpRequest();
        xhr.open("POST", 'http://127.0.0.1:1234/test/saveFile.php');
        xhr.send(blob);
}
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
        file_put_contents("Test.pdf", file_get_contents('php://input'));
}
?>

SignEncrypt operations code samples

Create a certificate from raw data

/* X509 data, as PEM or raw DER format, given as an hexadecimal string */
var x509 = "308206 ...";
var byteArray = new Uint8Array(x509.match(/.{2}/g).map(e => parseInt(e, 16)));
var blobCert = new Blob([byteArray], {type: "application/octet-stream"});
SCWS.createCertificate(blobCert).then(function(certificate) {
        console.log(certificate);
});

Sign a document

blob = getBlobFromLocal("input");
SCWS.requestCertificates(function(certificates) {
        return certificates;
}).then(function(certificates){
        SCWS.requestPrivateKey(certificates[0], false, function(pKey, cert){
                SCWS.signDocument(blob, pKey, cert, {format: "PADES", hashAlgorithm: "sha256"}).then(function(signedBlob){
                        downloadBlobLocal(signedBlob, "Test_signed.pdf");
                }, function(err) {console.log(err);});
        });
});

Encrypt a document

blob = getBlobFromLocal("input");
SCWS.requestCertificates(function(certificates) {
        SCWS.encryptDocument(blob, certificates).then(function(signedBlob){
                log("Encryption has succeeded.");
                downloadBlobLocal(signedBlob, "Test_encrypted.p7");
        }, function(err) {console.log(err);});
        return certificates;
});

SignEncrypt a document

blob = getBlobFromLocal("input");
SCWS.requestCertificates(function(certificates) {
        return certificates;
}).then(function(certificates) {
        SCWS.requestPrivateKey(certificates[0], false, function(pKey, cert) {
                SCWS.signEncryptDocument(blob, pKey, cert, cert, {hashAlgorithm: "sha256"}).then(function(signEncryptedBlob){
                        downloadBlobLocal(signEncryptedBlob, "Test_signEncrypted.p7");
                }, function(err) {console.log(err);});
        });
});

Verify a signature

CADES attached signature

<div id="filediv">
        <label for="input">Input Blob</label>
        <input id="input" type="file">
</div>
var blob = getBlobFromLocal("input");
SCWS.verifyDocument(blob, {format: "CADES_ATTACHED"}, undefined, downloadBlobLocal).then(function(verifResult){
        console.log(verifResult);
}, function(err) {console.log(err);});

CADES detached signature

<div id="filediv">
        <label for="input">Input Blob</label>
        <input id="input" type="file">
</div>
<div id="filediv">
        <label for="input2">Detached Blob</label>
        <input id="input2" type="file">
</div>
var blob = getBlobFromLocal("input");
var detachedBlob = getBlobFromLocal("input2");
SCWS.verifyDocument(blob, {format: "CADES_DETACHED"}, detachedBlob).then(function(verifResult){
        console.log(verifResult);
}, function(err) {console.log(err);});

Decrypt a document

function callbackDecrypt(recipientsList, decryptWith) {
        SCWS.requestCertificates(function(certificates) {
                return SCWS.matchIssuerAndSerialsWithCerts(recipientsList, certificates).then(function(result) {
                        for (let i = 0; i < certificates.length; i++) {
                                const index = result.indexOf(certificates[i]._handle);
                                if (index != -1)
                                        return certificates[i];
                        }
                });
        }).then(function(certificate) {
                SCWS.requestPrivateKey(certificate, false, function(pKey, cert) {
                        decryptWith(pKey, cert);
                });
        });
}

var blob = getBlobFromLocal("input");

SCWS.decryptDocument(blob, callbackDecrypt).then(function(blob){
        downloadBlobLocal(blob, "Test_decrypted");
}, function(err) {console.log(err);});

DecryptVerify a document

function callbackDecrypt(recipientsList, decryptWith) {
        SCWS.requestCertificates(function(certificates) {
                return SCWS.matchIssuerAndSerialsWithCerts(recipientsList, certificates).then(function(result) {
                        for (let i = 0; i < certificates.length; i++) {
                                const index = result.indexOf(certificates[i]._handle);
                                if (index != -1)
                                        return certificates[i];
                        }
                });
        }).then(function(certificate) {
                SCWS.requestPrivateKey(certificate, false, function(pKey, cert) {
                        decryptWith(pKey, cert);
                });
        });
}

blob = getBlobFromLocal("input");

SCWS.decryptVerifyDocument(blob, callbackDecrypt, downloadBlobLocal).then(function(verifResult){
        console.log(verifResult);
}, function(err) {console.log(err);});