gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 04:30:22 27 4
gpt4 key购买 nike

使用 Google Cloud IAM api,我正在为服务帐户生成一个 PKCS12 私钥。默认情况下, key 密码为“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);
}
}

关于java - 以编程方式更改 p12 证书密码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44015823/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com