use of org.bouncycastle.asn1.ocsp.Signature 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.asn1.ocsp.Signature in project athenz by yahoo.
the class Crypto method main.
public static void main(String[] args) throws CryptoException {
if (args.length >= 2) {
String op = args[0];
if ("sign".equals(op)) {
if (args.length == 3) {
String sig = Crypto.sign(args[1], Crypto.loadPrivateKey(new File(args[2])));
System.out.println(sig);
System.exit(0);
}
} else if ("verify".equals(op)) {
if (args.length == 4) {
if (Crypto.verify(args[1], Crypto.loadPublicKey(new File(args[2])), args[3])) {
System.out.println("Verified.");
} else {
System.out.println("NOT VERIFIED");
}
System.exit(0);
}
} else if ("public".equals(op)) {
if (args.length == 2) {
String pub = encodedFile(new File(args[1]));
// throws if something is wrong
Crypto.loadPublicKey(ybase64DecodeString(pub));
System.out.println(pub);
System.exit(0);
}
} else if ("private".equals(op)) {
if (args.length == 2) {
try {
String priv = encodedFile(new File(args[1]));
// throws if something is wrong
Crypto.loadPrivateKey(ybase64DecodeString(priv));
System.out.println(priv);
System.exit(0);
} catch (Exception e) {
System.out.println("*** " + e.getMessage());
System.exit(1);
}
}
}
}
System.out.println("usage: r Crypto private privateKeyFile");
System.out.println("usage: r Crypto public publicKeyFile");
System.out.println("usage: r Crypto sign msg privateKeyFile");
System.out.println("usage: r Crypto verify msg privateKeyFile signature");
System.exit(1);
}
use of org.bouncycastle.asn1.ocsp.Signature in project athenz by yahoo.
the class Crypto method verify.
/**
* Verify the signed data with given digest algorithm and the private key against the ybase64 encoded signature.
* @param message the message to sign, as a UTF8 string
* @param key the public key corresponding to the signing key
* @param signature the ybase64 encoded signature for the data
* @param digestAlgorithm supported values SHA1 and SHA256
* @return true if the message was indeed signed by the signature.
* @throws CryptoException for any issues with provider/algorithm/signature/key
*/
public static boolean verify(String message, PublicKey key, String signature, String digestAlgorithm) throws CryptoException {
try {
byte[] sig = ybase64Decode(signature);
String signatureAlgorithm = getSignatureAlgorithm(key.getAlgorithm(), digestAlgorithm);
java.security.Signature signer = java.security.Signature.getInstance(signatureAlgorithm, BC_PROVIDER);
signer.initVerify(key);
signer.update(utf8Bytes(message));
return signer.verify(sig);
} catch (NoSuchProviderException e) {
LOG.error("verify: Caught NoSuchProviderException, check to make sure the provider is loaded correctly.");
throw new CryptoException(e);
} catch (NoSuchAlgorithmException e) {
LOG.error("verify: Caught NoSuchAlgorithmException, check to make sure the algorithm is supported by the provider.");
throw new CryptoException(e);
} catch (SignatureException e) {
LOG.error("verify: Caught SignatureException.");
throw new CryptoException(e);
} catch (InvalidKeyException e) {
LOG.error("verify: Caught InvalidKeyException, invalid key type is being used.");
throw new CryptoException(e);
}
}
use of org.bouncycastle.asn1.ocsp.Signature in project athenz by yahoo.
the class Crypto method hmac.
/**
* Sign the message with the shared secret using HmacSHA256
* The result is a ybase64 (url safe) string.
* @param message the UTF-8 string to be signed
* @param sharedSecret the secret to sign with
* @return the ybase64 representation of the signature.
* @throws CryptoException for any issues with provider/algorithm/signature/key
*/
public static String hmac(String message, String sharedSecret) throws CryptoException {
// this has not been optimized!
String method = "HmacSHA256";
byte[] bsig = null;
try {
javax.crypto.Mac hmac = javax.crypto.Mac.getInstance(method);
javax.crypto.spec.SecretKeySpec secretKey = new javax.crypto.spec.SecretKeySpec(utf8Bytes(sharedSecret), method);
hmac.init(secretKey);
bsig = hmac.doFinal(message.getBytes());
} catch (NoSuchAlgorithmException e) {
LOG.error("hmac: Caught NoSuchAlgorithmException, check to make sure the algorithm is supported by the provider.");
throw new CryptoException(e);
} catch (InvalidKeyException e) {
LOG.error("hmac: Caught InvalidKeyException, incorrect key type is being used.");
throw new CryptoException(e);
}
return ybase64(bsig);
}
use of org.bouncycastle.asn1.ocsp.Signature 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错误,请检查输入参数");
}
}
Aggregations