密钥库中的 privateKey 返回 null

privateKey in keystore is returning null

提问人:shaik-ameen104 提问时间:11/15/2023 更新时间:11/15/2023 访问量:16

问:

public static PrivateKey getPrivateKey (KeyStore keystore, String keyId, char[] keyPwd) 
    throws BenefitsException {
      PrivateKey privateKey = null;
     try {
     if (keystore == null || keyPwd== null || keyId == null
     || "".equals(keyId)) {
       return privateKey;
      }
    else 
    {

    privateKey = (PrivateKey) keystore.getKey(keyId, keyPwd);
    }

    } catch (NoSuchAlgorithmException |
    UnrecoverableKeyException
    | KeyStoreException e) {
      throw new BenefitsException("Error in getPrivateKey method : ", e);
     return privateKey;

这是我的测试方法,有没有人弄清楚为什么 privatekey 返回 null

@Test public void getPrivateKey_ExceptionTest() 抛出 Exception{

    KeyStore keystoreMock = Mockito.mock (KeyStore.class);

    FieldUtils.writeField(keystoreMock, "keyStoreSpi", Mockito.mock (KeyStoreSpi.class), true);
    FieldUtils.writeField(keystoreMock, "initialized", true, true);



   char[] pwd= {'c', 'h', 'a', 'n', 'g', 'e', 'i', 't'};

   cryptoUtils.getPrivateKey(keystoreMock, "somestring", pwd);

   }
spring-boot junit4 junit5

评论


答:

0赞 beatngu13 11/22/2023 #1

我假设这是因为您没有在您的 上存该方法,因此您得到了默认答案。getKeykeyStoreMocknull

尝试如下操作:

String keyId = "keyId";
char[] keyPwd = {'c', 'h', 'a', 'n', 'g', 'e', 'i', 't'};
PrivateKey expectedPrivateKey = /* ... */
Mockito.when(keystoreMock.getKey(keyId, keyPwd).thenReturn(expectedPrivateKey);