I am working with Cordova and forge library and browser's Web Crypto API to perform sign and importKey operations. Nonetheless, Web Crypto API on Android device only offers crypto.getRandomValues() and SubtleCrypto is undefined (crypto.subtle). So I thought adding Web Crypto API shrim and its dependancy Promiz would fix this reference missing, but nothing has changed. Any idea please?
Debugging on PC in Chrome 52.0.2743.116 offers full Web Crypto API, however on Android device with Chrome version 52.0.2743.98 with Android 4.4.4. the Web API is limited only to crypto.getRandomValues().
I'am basically rewriting answer from How to load a PKCS#12 Digital Certificate with Javascript WebCrypto API
Code example:
Inside index.html
<script src="lib/promiz.min.js"></script>
<script src="lib/webcrypto-shim.js"></script>
Inside javascript file
//working with forge without issue
var pkcs12Der = forge.util.decode64(pk);
var pkcs12Asn1 = forge.asn1.fromDer(pkcs12Der);
var pkcs12 = forge.pkcs12.pkcs12FromAsn1(pkcs12Asn1, false, "password");
console.log(pkcs12);
privateKey = null;
// load keypair and cert chain from safe content(s)
for (var sci = 0; sci < pkcs12.safeContents.length; ++sci) {
var safeContents = pkcs12.safeContents[sci];
for (var sbi = 0; sbi < safeContents.safeBags.length; ++sbi) {
var safeBag = safeContents.safeBags[sbi];
// this bag has a private key
if (safeBag.type === forge.pki.oids.keyBag) {
//Found plain private key
privateKey = safeBag.key;
} else if (safeBag.type === forge.pki.oids.pkcs8ShroudedKeyBag) {
// found encrypted private key
privateKey = safeBag.key;
} else if (safeBag.type === forge.pki.oids.certBag) {
// this bag has a certificate...
}
}
}
//function for importingKey
function _importCryptoKeyPkcs8(privateKey, extractable) {
var privateKeyInfoDerBuff = _privateKeyToPkcs8(privateKey);
//import key will not work due to missing reference crypto.subtle
return window.crypto.subtle.importKey(
'pkcs8',
privateKeyInfoDerBuff, {
name: "RSASSA-PKCS1-v1_5",
hash: {
name: "SHA-256"
}
},
extractable, ["sign"]);
}
_importCryptoKeyPkcs8(privateKey, true).
then(function(cryptoKey) {
//sign will not work due to missing reference crypto.subtle
window.crypto.subtle.sign({
name: "RSASSA-PKCS1-v1_5"
},
cryptoKey,
digestToSignBuf)
.then(function(signature2) {
});
});