【问题标题】:Programmatically change p12 certificate password?以编程方式更改 p12 证书密码?
【发布时间】:2017-05-17 04:47:14
【问题描述】:

使用 Google Cloud IAM api,我正在为服务帐户生成 PKCS12 私钥。默认情况下,密钥密码为“notasecret”。如何以编程方式将其更改为更安全的内容?

import com.google.api.services.iam.v1.model.*;

Iam iam = googleIamClient(googleAppCredentials()); // helper method

String name = "projects/" + projectId + "/serviceAccounts/" + serviceAccountEmail;

CreateServiceAccountKeyRequest req = new CreateServiceAccountKeyRequest();
req.setPrivateKeyType("TYPE_PKCS12_FILE");

ServiceAccountKey key = iam.projects().serviceAccounts().keys().create(name, req).execute();

// equivalent to: byte[] privateKeyByteData = Base64.getDecoder().decode(serviceAccountKey.getPrivateKeyData());
byte[] privateKeyData = key.decodePrivateKeyData();

// what now?

【问题讨论】:

    标签: java google-cloud-platform pkcs#12


    【解决方案1】:

    这将更改 Google Cloud IAM PKCS12 证书的密码,并且可能会推广到其他人:

    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.security.*;
    import java.security.cert.*;
    
    public byte[] changePKCS12KeyPassword(byte[] privateKeyData, String oldPassword, String newPassword) {
        try {
            KeyStore newKs = KeyStore.getInstance("PKCS12");
            newKs.load(null, null);
    
            KeyStore ks = KeyStore.getInstance("PKCS12");
            ks.load(new ByteArrayInputStream(privateKeyData), oldPassword.toCharArray());
            Enumeration<String> aliases = ks.aliases();
    
            while (aliases.hasMoreElements()) {
                String alias = aliases.nextElement();
                Key privateKey = ks.getKey(alias, oldPassword.toCharArray());
                java.security.cert.Certificate[] certificateChain = ks.getCertificateChain(alias);
                newKs.setKeyEntry(alias, privateKey, newPassword.toCharArray(), certificateChain);
            }
    
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
    
            newKs.store(baos, newPassword.toCharArray());
    
            return baos.toByteArray();
        } catch (KeyStoreException
                | CertificateException
                | NoSuchAlgorithmException
                | UnrecoverableKeyException
                | IOException e) {
            throw new RuntimeException(e);
        }
    }
    

    【讨论】:

    • 这花了好几个小时才弄明白。希望这对其他人有帮助!
    • 谢谢@Fraser Harris..你帮了我很多!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-23
    • 2012-01-19
    • 2020-01-31
    • 1970-01-01
    • 2019-05-22
    • 2020-11-08
    相关资源
    最近更新 更多