【问题标题】:JWT implementation in Java using .pem file使用 .pem 文件在 Java 中实现 JWT
【发布时间】:2021-07-01 15:40:26
【问题描述】:

想知道 Java 中的 JWT 实现(生成令牌)是否只能通过密钥库中的 .jks 文件才能实现,我们是否也可以使用 .pem(证书和密钥)文件来实现?

我想将 .jks 文件存储在运行我的应用程序的 PaaS 提供商提供的安全位置,并且此服务不允许存储物理文件,而是二进制内容的编码格式可以是存储在我们必须通过解码引用的键值对中。但是,当我这样做时,我得到一个 Invalid keystore 错误。因此我想知道 .jks 是否是 JWT 令牌生成的命令?

【问题讨论】:

  • 不,.jks 对于 JWT 令牌生成不是强制性的。请在您使用密钥库文件的地方添加代码 sn-p
  • KeyStore keystore = KeyStore.getInstance("jks");
  • //从Keystore证书形成私钥的步骤 KeyStore keystore = KeyStore.getInstance("jks"); keystore.load(new FileInputStream(file), jwtstorePassword.toCharArray()); PrivateKey privateKey = (PrivateKey) keystore.getKey(jwtstoreAlias, jwtstorePassword.toCharArray()); // 将上述步骤中使用的证书形成为“file”的步骤 tmpFileCert = File.createTempFile("certfilejwt", ".jks"); fileWriter = new FileWriter(tmpFileCert);字符串 base64String = jwtValue; byte[] bytedecryptMessage = java.util.Base64.getDecoder().decode(base64String);
  • String decodedString = new String(bytedecryptMessage); fileWriter.write(decodedString);这里的 jwtValue 是存储在 PaaS 提供程序的安全仓库中的 .jks 文件 [base64 -w 0 certfile.jks] 的编码版本。

标签: java jwt


【解决方案1】:

根据您的要求,您不想使用Keystore & 而不是直接想读取私钥和公钥(或公共证书),您可以通过以下方式轻松实现。我添加了 apache 编解码器库依赖 import org.apache.commons.codec.binary.Base64; 用于 Base64 解码。

public static RSAPrivateKey readPrivateKey(File file) throws Exception {
    String key = new String(Files.readAllBytes(file.toPath()), Charset.defaultCharset());

    String privateKeyPEM = key.replace("-----BEGIN PRIVATE KEY-----", "")
        .replaceAll(System.lineSeparator(), "").replace("-----END PRIVATE KEY-----", "");

    byte[] encoded = Base64.decodeBase64(privateKeyPEM);

    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
    return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
  }

// to call above code
// private.key in PEM format
File file = new File("private.key");
PrivateKey key = readPrivateKey(file);

根据要求读取公钥和公共证书可以做类似的事情。

【讨论】:

  • 非常感谢您的即时回复。我尝试了同样的方法,现在我收到以下错误。将检查相同。 “java.security.spec.InvalidKeySpecException:java.security.InvalidKeyException:IOException:DerInputStream.getLength():lengthTag=40,太大了。”
  • @dev2021 你找到解决上述异常的方法了吗? “java.security.spec.InvalidKeySpecException:java.security.InvalidKeyException:IOException:DerInputStream.getLength():lengthTag=40,太大了。”
  • 还没有@Mihir...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-11-27
  • 2016-11-02
  • 1970-01-01
  • 2022-01-04
  • 2017-02-08
  • 2016-10-02
  • 2019-05-26
相关资源
最近更新 更多