6
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

node.js で公開鍵/秘密鍵によるデータの暗号化/復号

Posted at
import keypair from 'keypair'
import crypto from 'crypto'

const encrypt = (raw, publicKey) => {
  const encrypted = crpyto.publicEncrypt(publicKey, new Buffer(raw))
  return encrypted.toString('base64')
}

const decrypt = (encrypted, privateKey)=> {
  const decrypted = privateDecrypt(privateKey, new Buffer(encrypted, 'base64'))
  return decrypted.toString('utf8')
}

const pair = keypair()
const data = 'foo bar baz'

const encrypted = encrypt(data, pair.public)
console.log(encrypted)
const decrypted = decrypt(encrypted, pair.private)
console.log(decrypted)

注意: 簡単のため npm の keypair モジュールを使って公開鍵、秘密鍵を生成しているが、メモリ操作などによって脆弱な鍵を生成させられる可能性が排除できないので、 実際には openssl などの信頼できる実装を使ってください。

6
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?