【发布时间】:2020-08-26 06:03:42
【问题描述】:
我收到此错误:
com.nimbusds.jose.JOSEException:无效的私有 RSA 密钥:密钥库操作失败
还有我的 java.class:
public class MyClass {
private static final String ANDROID_PROVIDER = "AndroidKeyStore";
@RequiresApi(api = Build.VERSION_CODES.M)
public static PublicKey getPublicKeyAndCreateKeypairIfNotExists(String alias) throws GeneralSecurityException, IOException {
KeyStore keyStore = KeyStore.getInstance(ANDROID_PROVIDER);
keyStore.load(null);
if (!keyStore.containsAlias(alias) || keyStore.getCertificate(alias) == null) {
KeyGenParameterSpec spec = new KeyGenParameterSpec.Builder(
alias,
KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY)
.setBlockModes(KeyProperties.BLOCK_MODE_ECB)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1)
.setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512)
.build();
KeyPairGenerator generator = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_RSA, ANDROID_PROVIDER);
generator.initialize(spec);
generator.generateKeyPair();
}
return keyStore.getCertificate(alias).getPublicKey();
}
@RequiresApi(api = Build.VERSION_CODES.M)
public static PrivateKey getSecretKey(String alias) throws GeneralSecurityException, IOException {
KeyStore.Entry entry;
//Get Android KeyStore
KeyStore ks = KeyStore.getInstance(ANDROID_PROVIDER);
// Weird artifact of Java API. If you don't have an InputStream to load, you still need to call "load", or it'll crash.
ks.load(null);
// Load the key pair from the Android Key Store
entry = ks.getEntry(alias, null);
KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry)entry;
PrivateKey privateKey = privateKeyEntry.getPrivateKey();
return privateKey;
}
public static String createJWT(String alias) throws JSONException, GeneralSecurityException, IOException, JOSEException {
//
RSASSASigner signer = new RSASSASigner(getSecretKey(alias));
//signer.getJCAContext().setProvider(hsmProvider);
//
SignedJWT jwt = new SignedJWT(
new JWSHeader.Builder(JWSAlgorithm.RS256).keyID(alias).build(),
new JWTClaimsSet.Builder().subject("alice").build());
jwt.sign(signer);
String jwtString = jwt.serialize();
return jwtString;
}
}
具体是在执行createJWT方法的时候出现的就行了:
jwt.sign(signer);
显然密钥对的创建是令人满意的,因为我之前已经测试过它并且它没有给出任何错误,即使使用 ENCRYPT 和 DECRYPT 它也可以完美运行。问题出在 createJWT() 方法中。我真的不知道我做错了什么。
提前致谢
【问题讨论】:
-
你找到答案了吗?
标签: java jwt keystore android-keystore jwt-auth