如何生成用于 com.auth0 java-jwt 的 RSA 密钥?

How can I generate a RSA key for use with com.auth0 java-jwt?

https://github.com/auth0/java-jwt

声明为 JWT 设置算法应该像

一样简单
//RSA
RSAPublicKey publicKey = //Get the key instance
RSAPrivateKey privateKey = //Get the key instance
Algorithm algorithmRS = Algorithm.RSA256(publicKey, privateKey);

问题是我不知道如何在不接触文件系统的情况下创建 RSAPublicKey 和 RSAPrivateKey 实例。

  1. 它应该是安全的。
  2. 它不应该在文件系统上创建密钥,因为我计划通过另一种方法存储它。

通常这是我猜测的事情,直到我猜对为止,但考虑到它是密码学,我想做正确的事情。

keygen = KeyPairGenerator.getInstance("RSA");
        RSAKeyGenParameterSpec spec = new RSAKeyGenParameterSpec(2048, RSAKeyGenParameterSpec.F4); //What does F4 mean vs F0?
            keygen.initialize(spec);
            KeyPair keypair = keygen.generateKeyPair();
            PublicKey pub = keypair.getPublic(); //Wrong type, need RSAPublicKey
            PrivateKey priv = keypair.getPrivate(); //Wrong type, need RSAPrivateKey

您可以直接将 public 和私钥转换为 RSAPublicKeyRSAPrivateKey,因为您使用的是 RSA KeyPairGenerator

RSAPublicKey rsaPublicKey = (RSAPublicKey) keypair.getPublic();
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keypair.getPrivate();

您可以使用 key.getEncoded(); 获取关键内容(无需转换)并以您喜欢的任何方式将其存储为字节数组