Getting a PrivateKey object from a .p12 file in Java

前端 未结 4 1630
[愿得一人]
[愿得一人] 2020-12-05 06:59

As the title suggests, I have .p12 file required for google service account api access. In order to get the credential to connect to the api, there\'s a field .setServiceAcc

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-05 07:30

    The above suggestions did not work for me. Then I tried the one at http://www.java2s.com/Code/Java/Security/RetrievingaKeyPairfromaKeyStore.htm and it worked. Copy pasting it below

    import java.io.FileInputStream;
    import java.security.Key;
    import java.security.KeyPair;
    import java.security.KeyStore;
    import java.security.PrivateKey;
    import java.security.PublicKey;
    import java.security.cert.Certificate;
    
    public class Main {
      public static void main(String[] argv) throws Exception {
        FileInputStream is = new FileInputStream("your.keystore");
    
        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        keystore.load(is, "my-keystore-password".toCharArray());
    
        String alias = "myalias";
    
        Key key = keystore.getKey(alias, "password".toCharArray());
        if (key instanceof PrivateKey) {
          // Get certificate of public key
          Certificate cert = keystore.getCertificate(alias);
    
          // Get public key
          PublicKey publicKey = cert.getPublicKey();
    
          // Return a key pair
          new KeyPair(publicKey, (PrivateKey) key);
        }
      }
    }
    

提交回复
热议问题