简体   繁体   中英

How do encrypt a secret key using a password with tweetnacl-js?

https://github.com/dchest/tweetnacl-js comes highly recommended to me.

I have a project where the team want to display their keypair encoded as base64 on an ID. Of course they don't want to just display the secret key, but instead store an encrypted version of it. Something like this...

// do the encryption
let keyPair = tweetnacl.sign.keyPair();
let publicKey = tweetnacl.util.encodeBase64(keyPair.publicKey);
let signature = tweetnacl.util.encodeBase64(tweetnacl.sign.detached(tweetnacl.util.decodeUTF8(certData), keyPair.secretKey));
let secretKey = tweetnacl.util.encodeBase64(keyPair.secretKey);
let encryptedSecretKey = CryptoJS.AES.encrypt(secretKey, this.props.data.password).toString();

I've been advised against using CryptoJS. Is there a better way to do this using tweetnacl only?

Thanks.

tweetnacl has a symmetric encryption implementation called secretbox. You can encrypt anything you want like you do with AES, including your secret key.

Pseudocode:

var smkey = stringToUint8Array(keystring); // must be 32 bytes, pad it if you have to
var nonce = nacl.randomBytes(nacl.box.nonceLength);
var encryptedSecretKey = nacl.secretbox(secretKey, nonce, smkey);

Then you can convert the encrypted Uint8Array to string or base64 and use that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM