Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// Forge crypto package for node (https://www.npmjs.com/package/node-forge)
var forge = require('node-forge');
var pki = forge.pki;
var rsa = forge.rsa;
var ed25519 = forge.pki.ed25519;
var pem2jwk = require('pem-jwk').pem2jwk
const jwk2pem = require('pem-jwk').jwk2pem
const pify = require('pify');
const IPFS = require('ipfs')
const CKC = require('crypto-key-composer')
; (async () => {
let start = Date.now()
console.log(`Start ${start}`)
var tld = "tld"
var username = "username"
let password, salt, iterations, keySize, hash;
password = "password"
salt = `${tld}${username}`
iterations = 10000
keySize = 32
hash = 'sha2-256'
var derivedKey = IPFS.crypto.pbkdf2(password, salt, iterations, keySize, hash)
const bits = 256
// seed is a 32 byte uint8array
var buf = Buffer.from(derivedKey, 'utf8')
var encoded = await IPFS.multihashing.digest(buf, 'sha2-256')
//var decoded = IPFS.multihash.decode(encoded).digest
console.log(`IPFS Seed: \n${encoded.toString('base64')}\n`)
var md = forge.sha256.create(); // md = message digest, aka hash
md.update(derivedKey, "utf8");
var seed = md.digest().getBytes();// seed is a 32 byte uint8array
console.log(`Forge Seed: \n${Buffer.from(seed,'binary').toString('base64')} \n`)
var ed25519PrivateKey = await IPFS.crypto.keys.generateKeyPairFromSeed('ed25519', seed, bits) // returns Ed25519PrivateKey
var b64pk = Buffer.from(ed25519PrivateKey.bytes).toString('base64')
console.log('Ed25519PrivateKey: \n'+b64pk);
// Try to put it in PEM format
const myPrivatePemKey = CKC.composePrivateKey({
format: 'pkcs8-pem',
keyAlgorithm: 'ed25519',
keyData: {
seed: encoded
}
});
console.log(`pem Ed25519PrivateKey: \n${myPrivatePemKey} \n`)
//var myPrivateb64Key = await IPFS.crypto.keys.import(myPrivatePemKey) // cant, isnt RSA
IPFS.PeerId.createFromPrivKey( Buffer.from(b64pk,'base64') ).then(id => { console.log(`\n1.PeerId from password/seed: \n${id.toB58String()} \n `) });
IPFS.PeerId.createFromPrivKey(ed25519PrivateKey.bytes).then(id => { console.log(`\n2.PeerId from password/seed: \n${id.toB58String()} \n `) });
console.log(`End ${Date.now()-start} ms`);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment