use of org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder in project curiostack by curioswitch.
the class RequestNamespaceCertTask method exec.
@TaskAction
public void exec() {
ImmutableClusterExtension cluster = getProject().getExtensions().getByType(ClusterExtension.class);
final KeyPairGenerator keygen;
try {
keygen = KeyPairGenerator.getInstance("ECDSA", BouncyCastleProvider.PROVIDER_NAME);
} catch (NoSuchAlgorithmException | NoSuchProviderException e) {
throw new IllegalStateException("Could not find RSA, can't happen.", e);
}
keygen.initialize(256, new SecureRandom());
KeyPair keyPair = keygen.generateKeyPair();
PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(new X500Principal("CN=" + cluster.namespace() + ".ns.cluster.stellarstation.com"), keyPair.getPublic());
Stream<GeneralName> generalNames = Streams.concat(Stream.of(new GeneralName(GeneralName.dNSName, "*." + cluster.namespace()), new GeneralName(GeneralName.dNSName, "*." + cluster.namespace() + ".svc"), new GeneralName(GeneralName.dNSName, "*." + cluster.namespace() + ".svc.cluster.local")), cluster.extraNamespaceTlsHosts().stream().map(name -> new GeneralName(GeneralName.dNSName, name)));
GeneralNames subjectAltNames = new GeneralNames(generalNames.toArray(GeneralName[]::new));
ExtensionsGenerator extensions = new ExtensionsGenerator();
try {
extensions.addExtension(Extension.subjectAlternativeName, false, subjectAltNames);
p10Builder.setAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extensions.generate());
} catch (IOException e) {
throw new IllegalStateException("Could not encode cert name, can't happen.", e);
}
final ContentSigner signer;
try {
signer = new JcaContentSignerBuilder("SHA256withECDSA").build(keyPair.getPrivate());
} catch (OperatorCreationException e) {
throw new IllegalStateException("Could not find signer, can't happen.", e);
}
PKCS10CertificationRequest csr = p10Builder.build(signer);
StringWriter csrWriter = new StringWriter();
try (JcaPEMWriter pemWriter = new JcaPEMWriter(csrWriter)) {
pemWriter.writeObject(csr);
} catch (IOException e) {
throw new IllegalStateException("Could not encode csr, can't happen.", e);
}
String encodedCsr = Base64.getEncoder().encodeToString(csrWriter.toString().getBytes(StandardCharsets.UTF_8));
Map<Object, Object> csrApiRequest = ImmutableMap.of("apiVersion", "certificates.k8s.io/v1beta1", "kind", "CertificateSigningRequest", "metadata", ImmutableMap.of("name", cluster.namespace() + ".server.crt"), "spec", ImmutableMap.of("request", encodedCsr, "usages", ImmutableList.of("digital signature", "key encipherment", "server auth", "client auth")));
final byte[] encodedApiRequest;
try {
encodedApiRequest = OBJECT_MAPPER.writeValueAsBytes(csrApiRequest);
} catch (JsonProcessingException e) {
throw new IllegalStateException("Could not encode yaml", e);
}
ImmutableGcloudExtension config = getProject().getRootProject().getExtensions().getByType(GcloudExtension.class);
String command = config.download() ? CommandUtil.getGcloudSdkBinDir(getProject()).resolve("kubectl").toAbsolutePath().toString() : "kubectl";
getProject().exec(exec -> {
exec.executable(command);
exec.args("create", "-f", "-");
exec.setStandardInput(new ByteArrayInputStream(encodedApiRequest));
});
getProject().exec(exec -> {
exec.executable(command);
exec.args("certificate", "approve", cluster.namespace() + ".server.crt");
});
// Need to wait a bit for certificate to propagate before fetching.
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
// Gradle Exec seems to be flaky when reading from stdout, so use normal ProcessBuilder.
final byte[] certificateBytes;
try {
Process getCertProcess = new ProcessBuilder(command, "get", "csr", cluster.namespace() + ".server.crt", "-o", "jsonpath={.status.certificate}").start();
certificateBytes = ByteStreams.toByteArray(getCertProcess.getInputStream());
} catch (IOException e) {
throw new UncheckedIOException("Could not fetch certificate.", e);
}
String certificate = new String(Base64.getDecoder().decode(certificateBytes), StandardCharsets.UTF_8);
final JcaPKCS8Generator keyGenerator;
final PemObject keyObject;
try {
keyGenerator = new JcaPKCS8Generator(keyPair.getPrivate(), null);
keyObject = keyGenerator.generate();
} catch (PemGenerationException e) {
throw new IllegalStateException("Could not encode to pkcs8.", e);
}
StringWriter keyWriter = new StringWriter();
try (JcaPEMWriter pemWriter = new JcaPEMWriter(keyWriter)) {
pemWriter.writeObject(keyObject);
} catch (IOException e) {
throw new IllegalStateException("Could not encode csr, can't happen.", e);
}
String key = keyWriter.toString();
KubernetesClient client = new DefaultKubernetesClient();
Secret certificateSecret = new SecretBuilder().withMetadata(new ObjectMetaBuilder().withName("server-tls").withNamespace(cluster.namespace()).build()).withType("Opaque").withData(ImmutableMap.of("server.crt", Base64.getEncoder().encodeToString(certificate.getBytes(StandardCharsets.UTF_8)), "server-key.pem", Base64.getEncoder().encodeToString(key.getBytes(StandardCharsets.UTF_8)))).build();
client.resource(certificateSecret).createOrReplace();
}
use of org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder in project portal by ixinportal.
the class GenUtil method GenP10.
public static String GenP10(String userid, String subject, String alg) throws GenP10Exception {
if (!"".equalsIgnoreCase(userid)) {
if (keyMap.containsKey(userid)) {
throw new GenP10Exception("用户唯一标识【" + userid + "】不能重复");
}
} else {
throw new GenP10Exception("用户唯一标识不能为空");
}
KeyPairGenerator kpg = null;
try {
kpg = KeyPairGenerator.getInstance(alg);
} catch (NoSuchAlgorithmException e1) {
throw new GenP10Exception("输入秘钥对产生算法不正确:" + alg);
}
if ("SM2".equalsIgnoreCase(alg)) {
kpg.initialize(256);
} else {
kpg.initialize(2048);
}
KeyPair kp = kpg.generateKeyPair();
keyMap.put(userid, kp);
byte[] publickey = kp.getPublic().getEncoded();
final String pubAlg = kp.getPublic().getAlgorithm();
String sAlg = null;
try {
sAlg = AlgorithmId.get(pubAlg).getOID().toString();
} catch (NoSuchAlgorithmException e1) {
throw new GenP10Exception("输入秘钥对产生算法不正确:" + sAlg);
}
SubjectPublicKeyInfo spki = null;
if (sAlg.equals("1.2.156.10197.1.301")) {
spki = SubjectPublicKeyInfo.getInstance(publickey);
} else {
spki = new SubjectPublicKeyInfo(ASN1Sequence.getInstance(publickey));
}
if ("".equals(subject)) {
subject = "CN=defaultName";
}
X500Name x500 = new X500Name(subject);
PKCS10CertificationRequestBuilder prb = new PKCS10CertificationRequestBuilder(x500, spki);
ContentSigner signer = null;
PrivateKey privateKey = kp.getPrivate();
final Signature sign;
try {
if (privateKey.getAlgorithm().equals("SM2")) {
sign = Signature.getInstance("SM3withSM2");
} else {
sign = Signature.getInstance("SHA1withRSA");
}
sign.initSign(privateKey);
} catch (NoSuchAlgorithmException e) {
throw new GenP10Exception("输入秘钥对产生算法不正确:SHA1withRSA");
} catch (InvalidKeyException e) {
throw new GenP10Exception("无效的私钥信息");
}
signer = new ContentSigner() {
ByteArrayOutputStream originStream = new ByteArrayOutputStream();
public byte[] getSignature() {
try {
sign.update(this.originStream.toByteArray());
return sign.sign();
} catch (SignatureException e) {
throw new RuntimeException(e);
}
}
public OutputStream getOutputStream() {
return this.originStream;
}
public AlgorithmIdentifier getAlgorithmIdentifier() {
try {
return new AlgorithmIdentifier(AlgorithmId.get(pubAlg).getOID().toString());
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
};
PKCS10CertificationRequestHolder pr = prb.build(signer);
try {
return new String(Base64.encode(pr.getEncoded()));
} catch (IOException e) {
throw new GenP10Exception("产生CSR错误,请检查输入参数");
}
}
use of org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder in project xipki by xipki.
the class CaClientExample method genCsr.
protected static CertificationRequest genCsr(MyKeypair keypair, String subject, String challengePassword) throws GeneralSecurityException, OperatorCreationException {
X500Name subjectDn = new X500Name(subject);
PKCS10CertificationRequestBuilder csrBuilder = new PKCS10CertificationRequestBuilder(subjectDn, keypair.publicKeyInfo);
if (challengePassword != null && !challengePassword.isEmpty()) {
csrBuilder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_challengePassword, new DERPrintableString(challengePassword));
}
ContentSigner signer = buildSigner(keypair.privateKey, "SHA256");
return csrBuilder.build(signer).toASN1Structure();
}
use of org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder in project airavata by apache.
the class MyProxyLogon method generateCertificationRequest.
private PKCS10CertificationRequest generateCertificationRequest(String dn, KeyPair kp) throws Exception {
X500Name subject = new X500Name(dn);
PublicKey pubKey = kp.getPublic();
PrivateKey privKey = kp.getPrivate();
AsymmetricKeyParameter pubkeyParam = PublicKeyFactory.createKey(pubKey.getEncoded());
SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(pubkeyParam);
PKCS10CertificationRequestBuilder builder = new PKCS10CertificationRequestBuilder(subject, publicKeyInfo);
AlgorithmIdentifier signatureAi = new AlgorithmIdentifier(OIWObjectIdentifiers.sha1WithRSA);
BcRSAContentSignerBuilder signerBuilder = new BcRSAContentSignerBuilder(signatureAi, AlgorithmIdentifier.getInstance(OIWObjectIdentifiers.idSHA1));
AsymmetricKeyParameter pkParam = PrivateKeyFactory.createKey(privKey.getEncoded());
ContentSigner signer = signerBuilder.build(pkParam);
return builder.build(signer);
}
use of org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder in project spring-cloud-digital-sign by SpringForAll.
the class ServerPKCSUtil method genCsr.
/**
* genCsr
*
* @param alg0 alg
* 密钥算法
* @return
*/
public static String genCsr(String alg0) {
if ("".equals(alg0)) {
alg = alg0;
}
// 产生秘钥对
KeyPairGenerator kpg = null;
try {
kpg = KeyPairGenerator.getInstance(alg);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
// 根据秘钥算法配置秘钥长度
if ("SM2".equalsIgnoreCase(alg)) {
kpg.initialize(256);
} else {
kpg.initialize(2048);
}
KeyPair kp = kpg.generateKeyPair();
securityKP = kp;
// 获取公钥以及公钥算法
byte[] publickey = kp.getPublic().getEncoded();
String pubAlg = kp.getPublic().getAlgorithm();
String sAlg = null;
try {
sAlg = AlgorithmId.get(pubAlg).getOID().toString();
} catch (NoSuchAlgorithmException e) {
}
SubjectPublicKeyInfo spki = null;
// 区分SM2和RSA
if (sAlg.equals("1.2.156.10197.1.301")) {
spki = SubjectPublicKeyInfo.getInstance(publickey);
} else {
spki = new SubjectPublicKeyInfo(ASN1Sequence.getInstance(publickey));
}
String subject = "CN=defaultName";
X500Name x500 = new X500Name(subject);
// 产生csr构造器
PKCS10CertificationRequestBuilder prb = new PKCS10CertificationRequestBuilder(x500, spki);
// 构建签名信息
ContentSigner signer = null;
PrivateKey privateKey = kp.getPrivate();
Signature sign = null;
try {
if (privateKey.getAlgorithm().equals("SM2")) {
sign = Signature.getInstance("SM3withSM2");
} else {
sign = Signature.getInstance("SHA1withRSA");
}
sign.initSign(privateKey);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
}
final Signature sign1 = sign;
signer = new ContentSigner() {
ByteArrayOutputStream originStream = new ByteArrayOutputStream();
public byte[] getSignature() {
try {
sign1.update(originStream.toByteArray());
return sign1.sign();
} catch (SignatureException e) {
throw new RuntimeException(e);
}
}
public OutputStream getOutputStream() {
return originStream;
}
public AlgorithmIdentifier getAlgorithmIdentifier() {
try {
return new AlgorithmIdentifier(AlgorithmId.get(sign1.getAlgorithm()).getOID().toString());
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
};
PKCS10CertificationRequestHolder pr = prb.build(signer);
try {
return new String(Base64.encode(pr.getEncoded()));
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Aggregations