Reputation: 4207
I need to get the private key from a p12 file I've been given. I tried using the forge library and wrote the following code.
var forge = require('node-forge');
var fs = require('fs');
var p12File = fs.readFileSync("C:/Users/macilamanym/Desktop/certs/mayoorancert.p12");
//var privateKey = p12ToPem(p12File, "qwerty");
var p12Der = forge.util.decode64(p12File);
// get p12 as ASN.1 object
var p12Asn1 = forge.asn1.fromDer(p12Der);
// decrypt p12 using the password 'password'
var p12 = forge.pkcs12.pkcs12FromAsn1(p12Asn1, 'qwerty');
console.log(p12);
But its throwing the following error.
G:\Projects\Tests\NodeJSTest\node_modules\node-forge\js\util.js:1569
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, '');
^
TypeError: input.replace is not a function
at Object.util.decode64 (G:\Projects\Tests\NodeJSTest\node_modules\node-forge\js\util.js:1569:17)
at Object.<anonymous> (G:\Projects\Tests\NodeJSTest\index.js:9:25)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:139:18)
at node.js:968:3
What have I done wrong here? Is there a better way to get the private key from the p12 file? Please advice.
Also please note that I have only been given the password for the private key. Name of the private key is not known. So should be a solution where I don't need to give the private key name to get it from the p12.
Upvotes: 2
Views: 5595
Reputation: 7893
I was able to get p12 from file by using this method:
var forge = require('node-forge');
var fs = require('fs');
var keyFile = fs.readFileSync('path/to/your/p12/file.p12');
var keyBase64 = keyFile.toString('base64');
var p12Der = forge.util.decode64(keyBase64);
var p12Asn1 = forge.asn1.fromDer(p12Der);
var p12 = forge.pkcs12.pkcs12FromAsn1(p12Asn1, 'password');
console.log(p12);
I'm getting p12
file via fs
as string and encode it to base64
.
I hope it will help.
Upvotes: 3