我使用的JWT库需要DER格式的RSA私钥。我要使用的密钥作为PEM文件提供,因此我需要以编程方式从PEM转换为DER。
我将密钥放置在名为key.pem
的文件中:
-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDgeHwsMzBD1Z+f
yZmNO8lw+kjfJXAOcdA682jU98O9vpFTcx8pz1MtCwQ9dSCjGOZoLF0yjVTLTRAY
Zcnp2f2zACKhgZokF9NtX+yxVjyDESoWJKF9756UlfK2c4UR1xDrRR05ERJPD8qp
NhDCfK5C8ttQfC4w7FMWk83qCHI/bMfzEmwN/lX7SeD6Iqvf0BlGNB8zCOEtGQix
vLhj2LIB+cn7ykU9ziyCLQqHLkMYxWFFSlBh2jA0Sk3NnDBP8Z5BEeWQjh0CYInL
k13mpgADu1kOkU7uRDTTRtjDCBDAotxgAGClAztBySk25nfmR4HzNqObjkMGf/Ka
75fJjfqPAgMBAAECggEAJ5NGfTp3J3aJ4o+WGW7xiJAv+dutYnaReltA389g/NqU
36wb0fDCHt5i3H0CiI7SzIoJ0mhVi1RmYo7LpwWuc3kyIdxqMzPaLF3tqqRkHc2Q
aIAD0uLEyDiZpq4+R1NuIbS5Pr7yResoVWX5VXjK9nW/0fRa5ng7++6KLtlXXzP3
h4EEG6lckJm3JNp0npZPHOWH3vSMorLJmk7atF5sOU4hVeXIy7LYJg4NA39rCs+J
YVgcpKSqeZ1TamWJIa5pwo+6t8GRn93ibpe7tXxydjynkLTiv1oOQFDEUTEQXu2/
OjczS+d1XYUZdxcTuVLqhy19C/8F9Y6BFjvILOV/vQKBgQD31xsIVxBD4uuJHHbM
ywEdncYtoy3gtROSGd++HUAtXvT5o+QXOT5nqUBK/pA8qfio190R3Z5WXll35UU1
IukIBZMxn0QzUgkS3sG7/weNGFKI8n3xV37jE4EZwpamMLLWeHWSYoZZJ6he9RJ8
81GbhUkVf3zNlVAosw75tgT6fQKBgQDn3GlHfsEiMTig5rVxf1XlkzZIOZUQl8Lm
fUQaE1ivW/2FfTfR4gz8eM7nF4YvPSWKAKFpFVkPkYzNGH8jVvZoxOURYp7nyOxj
wsCWgC5JNQI2pm3XEHdckzpIdSmslj/Y4nKtfSaisUPfzK2OFqDegbDMeo+53mej
9WU47kmK+wKBgQDX+sS8B+NMxbusyPlejqpyPMQvkTyxzhs3/wRUkPkUkOO7iW+E
LYaMn5o/wIfB1f20ZilpIFCTw7UEHvCo1btuGi2j2L9+Wcc+gpEiW6Ug+Ek0vt2y
LCWPjbe70y+ltFqlPGR5JRMfLsgzuC5cZU6A0S5XZbpFDhHE5gXu5wh/oQKBgQCV
5VAG0bKIqWuj0iNhceIVXnvMa7WsGYD+Q+PAO9us2vrmzxJEVTDyFCQnEHVGmvBm
7ItthUijoQR3H6wqK7F4ADrbZ3e1/5ab1C9v3QSPfX6l2CjQzitspR4b8+ryUdyL
GbLr6CoPKizoRcm6P3TXBN9JAr9ieZ9lR2OeT6cp+wKBgG24MBofgUZk+qsv+Ckn
ascTXiN+3HBymWlZTv6ASAzfAxDk4VKPcxFwGakZHzn6MEXLSXsrAogWEub4w++K
morv11PVwylhia+l6WBwNNU/Jh7U7KqTTcuU0PqXwkXOrTxEmsX1VU43FLTuNSLx
+qqh3ZHwn7zj4WNi5f9TDTU8
-----END PRIVATE KEY-----
我生成了一个名为key.der
的文件:
openssl rsa -in key.pem -outform DER -out key.der
以下代码有效:
fn main() {
let mut header = jsonwebtoken::Header::default();
header.alg = jsonwebtoken::Algorithm::RS256;
let claims = ();
let _jwt = jsonwebtoken::encode(&header, &claims, include_bytes!("key.der")).unwrap();
}
但是以下代码会产生错误:
fn main() {
let mut header = jsonwebtoken::Header::default();
header.alg = jsonwebtoken::Algorithm::RS256;
let claims = ();
let pem = pem::parse(include_str!("key.pem")).unwrap();
let jwt = jsonwebtoken::encode(&header, &claims, &pem.contents).unwrap();
}
确切的错误消息是:
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Error(InvalidRsaKey)', src/libcore/result.rs:999:5
note: Run with `RUST_BACKTRACE=1` environment variable to display a backtrace.
我的Cargo.toml
[package]
name = "tmp"
version = "0.1.0"
edition = "2018"
[dependencies]
pem = "=0.6.0"
jsonwebtoken = "=6.0.1"