以编程方式更改 p12 证书密码



使用 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?

这将更改 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);
    }
}

最新更新