// JavaScript Document
var keyPair;
var pemPublicKey;
var pemPrivateKey;
var _spki;
var _pkcs8;
window.crypto.subtle.generateKey({
name: "RSA-OAEP",
modulusLength: 2048,
publicExponent: new Uint8Array([1, 0, 1]), // 24 bit representation of 65537
hash: {name: "SHA-512"}
}, true, ["encrypt", "decrypt"])
.then(function(newKeyPair) {
keyPair = newKeyPair;
return keyPair;
})
.then(function(keyPair) {
window.crypto.subtle.exportKey('spki', keyPair.publicKey)
.then(function(spki) {
_spki = spki;
var pemPublicKey = convertBinaryToPem(spki, "PUBLIC KEY");
document.writeln(pemPublicKey);
sendToPhp();
});
window.crypto.subtle.exportKey('pkcs8', keyPair.privateKey)
.then(function(pkcs8) {
_pkcs8 = pkcs8;
var pemPrivateKey = convertBinaryToPem(pkcs8, "PRIVATE KEY");
document.writeln(pemPrivateKey);
})
});
function sendToPhp() {
window.crypto.subtle.importKey('spki', _spki, {name:"RSA-OAEP", hash: {name: "SHA-512"}}, false, ["encrypt"])
.then(function(cryptokey) {
window.crypto.subtle.encrypt({ name: "RSA-OAEP"}, cryptokey, str2ab('mijn geheimpje') )
.then(function(encrypted){
//returns an ArrayBuffer containing the encrypted data
document.writeln(arrayBufferToBase64String(encrypted));
receivedFromPhp(arrayBufferToBase64String(encrypted));
});
});
}
function receivedFromPhp(encrypted) {
window.crypto.subtle.importKey('pkcs8', _pkcs8, {name:"RSA-OAEP", hash: {name: "SHA-512"}}, false, ["decrypt"])
.then(function(cryptokey) {
window.crypto.subtle.decrypt({ name: "RSA-OAEP"}, cryptokey, base64StringToArrayBuffer(encrypted) )
.then(function(decrypted){
//returns an ArrayBuffer containing the encrypted data
var decryp = ab2str(decrypted);
debugger;
});
});
}
function ab2str(buf) {
return String.fromCharCode.apply(null, new Uint16Array(buf));
}
function str2ab(str) {
var buf = new ArrayBuffer(str.length*2); // 2 bytes for each char
var bufView = new Uint16Array(buf);
for (var i=0, strLen=str.length; i<strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
}
function base64StringToArrayBuffer(base64) {
var binary_string = atob(base64);
var len = binary_string.length;
var bytes = new Uint8Array( len );
for (var i = 0; i < len; i++) {
bytes[i] = binary_string.charCodeAt(i);
}
return bytes.buffer;
}
function arrayBufferToBase64String(arrayBuffer) {
var byteArray = new Uint8Array(arrayBuffer)
var byteString = '';
for (var i=0; i<byteArray.byteLength; i++) {
byteString += String.fromCharCode(byteArray[i]);
}
return btoa(byteString);
}
function convertBinaryToPem(binaryData, label) {
var base64Cert = arrayBufferToBase64String(binaryData);
var pemCert = "-----BEGIN " + label + "-----\r\n";
var nextIndex = 0;
var lineLength;
while (nextIndex < base64Cert.length) {
if (nextIndex + 64 <= base64Cert.length) {
pemCert += base64Cert.substr(nextIndex, 64) + "\r\n";
} else {
pemCert += base64Cert.substr(nextIndex) + "\r\n";
}
nextIndex += 64;
}
pemCert += "-----END " + label + "-----\r\n";
return pemCert;
}