我正在尝试使用Jose (https://bitbucket.org/b_c/jose4j/wiki/Home)来生成一个签名的JsonWebToken。我在创建需要在令牌签名中使用的RsaKeyPairs时遇到了一个问题。
这是我用来生成公钥/私钥的代码,我需要将它转换为字符串,这样我就可以将它们存储在数据库中,然后检索它们。
WebKeyManager wkm = null;
Object obj;
EncryptionKey encKey = null;
RsaJsonWebKey rsaJsonWebKey = null;
try
{
wkm = new WebKeyManager();
int keySize = 512;
// Initialize KeyPairGenerator.
SecureRandom random = SecureRandom.getInstanceStrong(); //cryptographically strong random number generator
// Generate an RSA key pair, which will be used for signing and verification of the JWT, wrapped in a JWK
rsaJsonWebKey = RsaJwkGenerator.generateJwk(keySize, random.getProvider().getName(),random);
// Give the JWK a Key ID (kid), which is just the polite thing to do
rsaJsonWebKey.setKeyId(""+System.currentTimeMillis());
String json = rsaJsonWebKey.toJson(OutputControlLevel.INCLUDE_PRIVATE);
}
catch (Exception e)
{
e.printStackTrace();
}我遇到的问题是当我使用rsaJsonWebKey.toJson(OutputControlLevel.INCLUDE_PRIVATE)时
我得到了这个错误:
java.lang.ClassCastException: sun.security.mscapi.RSAPrivateKey cannot be cast to java.security.interfaces.RSAPrivateKey
at org.jose4j.jwk.RsaJsonWebKey.getRsaPrivateKey(RsaJsonWebKey.java:123)
at org.jose4j.jwk.RsaJsonWebKey.fillPrivateTypeSpecificParams(RsaJsonWebKey.java:135)
at org.jose4j.jwk.PublicJsonWebKey.fillTypeSpecificParams(PublicJsonWebKey.java:122)
at org.jose4j.jwk.JsonWebKey.toParams(JsonWebKey.java:166)
at org.jose4j.jwk.JsonWebKey.toJson(JsonWebKey.java:178)我尝试在Jose中调试代码,错误出现在PublicJsonWebKey类中,如下所示:
protected void fillPrivateTypeSpecificParams(Map<String,Object> params)
{
RSAPrivateKey rsaPrivateKey = getRsaPrivateKey();rsaPrivateKey为java.security.interfaces.RSAPrivateKey,而getRsaPrivateKey()返回org.jose4j.jwk.RsaJsonWebKey
我做错了什么?
我的需求是生成KeyPairs,将它们存储在数据库中的varchar类型字段或类似的字段中,然后无论何时需要,我都可以从数据库中检索字符串,将其转换回私有/公共密钥,并使用它们对令牌进行签名?
发布于 2017-07-11 21:09:33
经过一些研究,我发现如果我使用这个构造函数创建密钥
rsaJsonWebKey = RsaJwkGenerator.generateJwk(keySize); 那我就不明白这个错误了。
https://stackoverflow.com/questions/45034470
复制相似问题