Closed3
OpenSSLのRSA対照鍵を作成して、RS256のJWTを作成する

昔似たような記事を書いたが、古いので、OpenSSL 3系に対応したものを書く

2023/10/12時点で、最新のOpenSSLをインストールしてパスを通す
$ brew install openssl
$ brew list openssl
/opt/homebrew/Cellar/openssl@3/3.1.3/.bottle/etc/ (7 files)
/opt/homebrew/Cellar/openssl@3/3.1.3/bin/c_rehash
/opt/homebrew/Cellar/openssl@3/3.1.3/bin/openssl
/opt/homebrew/Cellar/openssl@3/3.1.3/include/openssl/ (135 files)
/opt/homebrew/Cellar/openssl@3/3.1.3/lib/libcrypto.3.dylib
/opt/homebrew/Cellar/openssl@3/3.1.3/lib/libssl.3.dylib
/opt/homebrew/Cellar/openssl@3/3.1.3/lib/engines-3/ (3 files)
/opt/homebrew/Cellar/openssl@3/3.1.3/lib/ossl-modules/legacy.dylib
/opt/homebrew/Cellar/openssl@3/3.1.3/lib/pkgconfig/ (3 files)
/opt/homebrew/Cellar/openssl@3/3.1.3/lib/ (4 other files)
/opt/homebrew/Cellar/openssl@3/3.1.3/share/doc/ (798 files)
/opt/homebrew/Cellar/openssl@3/3.1.3/share/man/ (5533 files)
$ /opt/homebrew/Cellar/openssl@3/3.1.3/bin/openssl version
OpenSSL 3.1.3 19 Sep 2023 (Library: OpenSSL 3.1.3 19 Sep 2023)
$ export PATH="/opt/homebrew/Cellar/openssl@3/3.1.3/bin:$PATH";openssl version
OpenSSL 3.1.3 19 Sep 2023 (Library: OpenSSL 3.1.3 19 Sep 2023)

RSA対照鍵の作成
openssl genrsa -out private.key 2048
サクッとDenoで作れないかと思ったけれど何をやっても、error: Uncaught Error: secretOrPrivateKey must be an asymmetric key when using RS256
になる。
後述するNode.jsではうまくいったので、鍵は問題ないのでESM周りの問題だと思う。djwt使うのが良い気がする。
denoだとうまくいかない
import fs from 'node:fs';
import path from 'node:path';
import jwt from 'npm:jsonwebtoken';
const __dirname = new URL('.', import.meta.url).pathname;
const privateKey = fs.readFileSync(path.join(__dirname, '../certs/private.key'));
const payload = {
foo: 'hoge',
};
const token = jwt.sign(payload, privateKey, {
algorithm: 'RS256',
expiresIn: '3600s',
});
console.log(token);
pnpm ts-node ./samples/bin/gen-test-jwt.ts
nodeだとうまくいく
import * as fs from 'fs';
import * as path from 'path';
import * as jwt from 'jsonwebtoken';
const privateKey = fs.readFileSync(path.join(__dirname, '../certs/private.key'));
const payload = {
foo: 'hoge',
};
const token = jwt.sign(payload, privateKey, {
algorithm: 'RS256',
expiresIn: '3600s',
});
console.log(token);
$ npm install -g jwt-cli
$ jwt [出力されたトークン]
出力結果
✻ Header
{
"alg": "RS256",
"typ": "JWT"
}
✻ Payload
{
"foo": "hoge",
"iat": 1697085001,
"exp": 1697088601
}
iat: 1697085001 2023/10/12 13:30:01
exp: 1697088601 2023/10/12 14:30:01
このスクラップは2023/10/14にクローズされました