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

时间:2017-05-17 04:47:14

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

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

1 个答案:

答案 0 :(得分:3)

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