use of org.bouncycastle.operator.OperatorCreationException in project athenz by yahoo.
the class ZTSClient method getAWSLambdaServiceCertificate.
/**
* For AWS Lambda functions generate a new private key, request a
* x.509 certificate based on the requested CSR and return both to
* the client in order to establish tls connections with other
* Athenz enabled services.
* @param domainName name of the domain
* @param serviceName name of the service
* @param account AWS account name that the function runs in
* @param provider name of the provider service for AWS Lambda
* @return AWSLambdaIdentity with private key and certificate
*/
public AWSLambdaIdentity getAWSLambdaServiceCertificate(String domainName, String serviceName, String account, String provider) {
if (domainName == null || serviceName == null) {
throw new IllegalArgumentException("Domain and Service must be specified");
}
if (account == null || provider == null) {
throw new IllegalArgumentException("AWS Account and Provider must be specified");
}
if (x509CsrDomain == null) {
throw new IllegalArgumentException("X509 CSR Domain must be specified");
}
// first we're going to generate a private key for the request
AWSLambdaIdentity lambdaIdentity = new AWSLambdaIdentity();
try {
lambdaIdentity.setPrivateKey(Crypto.generateRSAPrivateKey(2048));
} catch (CryptoException ex) {
throw new ZTSClientException(ZTSClientException.BAD_REQUEST, ex.getMessage());
}
// we need to generate an csr with an instance register object
InstanceRegisterInformation info = new InstanceRegisterInformation();
info.setDomain(domainName.toLowerCase());
info.setService(serviceName.toLowerCase());
info.setProvider(provider.toLowerCase());
final String athenzService = info.getDomain() + "." + info.getService();
// generate our dn which will be based on our service name
StringBuilder dnBuilder = new StringBuilder(128);
dnBuilder.append("cn=");
dnBuilder.append(athenzService);
if (x509CsrDn != null) {
dnBuilder.append(',');
dnBuilder.append(x509CsrDn);
}
// now let's generate our dsnName field based on our principal's details
StringBuilder hostBuilder = new StringBuilder(128);
hostBuilder.append(info.getService());
hostBuilder.append('.');
hostBuilder.append(info.getDomain().replace('.', '-'));
hostBuilder.append('.');
hostBuilder.append(x509CsrDomain);
StringBuilder instanceHostBuilder = new StringBuilder(128);
instanceHostBuilder.append("lambda-");
instanceHostBuilder.append(account);
instanceHostBuilder.append('-');
instanceHostBuilder.append(info.getService());
instanceHostBuilder.append(".instanceid.athenz.");
instanceHostBuilder.append(x509CsrDomain);
GeneralName[] sanArray = new GeneralName[2];
sanArray[0] = new GeneralName(GeneralName.dNSName, new DERIA5String(hostBuilder.toString()));
sanArray[1] = new GeneralName(GeneralName.dNSName, new DERIA5String(instanceHostBuilder.toString()));
try {
info.setCsr(Crypto.generateX509CSR(lambdaIdentity.getPrivateKey(), dnBuilder.toString(), sanArray));
} catch (OperatorCreationException | IOException ex) {
throw new ZTSClientException(ZTSClientException.BAD_REQUEST, ex.getMessage());
}
// finally obtain attestation data for lambda
info.setAttestationData(getAWSLambdaAttestationData(athenzService, account));
// request the x.509 certificate from zts server
Map<String, List<String>> responseHeaders = new HashMap<>();
InstanceIdentity identity = postInstanceRegisterInformation(info, responseHeaders);
try {
lambdaIdentity.setX509Certificate(Crypto.loadX509Certificate(identity.getX509Certificate()));
} catch (CryptoException ex) {
throw new ZTSClientException(ZTSClientException.BAD_REQUEST, ex.getMessage());
}
return lambdaIdentity;
}
use of org.bouncycastle.operator.OperatorCreationException in project athenz by yahoo.
the class SelfCertSignerFactory method create.
@Override
public CertSigner create() {
// extract the private key for this self cert signer
final String pKeyFileName = System.getProperty(ZTSConsts.ZTS_PROP_SELF_SIGNER_PRIVATE_KEY_FNAME);
final String pKeyPassword = System.getProperty(ZTSConsts.ZTS_PROP_SELF_SIGNER_PRIVATE_KEY_PASSWORD);
final String csrDn = System.getProperty(ZTSConsts.ZTS_PROP_SELF_SIGNER_CERT_DN, "cn=Self Signed Athenz CA,o=Athenz,c=US");
if (pKeyFileName == null) {
LOGGER.error("No private key path available for Self Cert Signer Factory");
return null;
}
File caKey = new File(pKeyFileName);
PrivateKey caPrivateKey = Crypto.loadPrivateKey(caKey, pKeyPassword);
// now generate a CSR for our own CA and self sign it
String csr = null;
try {
csr = Crypto.generateX509CSR(caPrivateKey, csrDn, null);
} catch (OperatorCreationException | IOException ex) {
LOGGER.error("Unable to generate X509 CSR for dn: " + csrDn + ", error: " + ex.getMessage());
return null;
}
// generate our self signed certificate
X500Principal subject = new X500Principal(csrDn);
X500Name issuer = X500Name.getInstance(subject.getEncoded());
PKCS10CertificationRequest certReq = Crypto.getPKCS10CertRequest(csr);
X509Certificate caCertificate = Crypto.generateX509Certificate(certReq, caPrivateKey, issuer, 30 * 24 * 60, true);
return new SelfCertSigner(caPrivateKey, caCertificate);
}
use of org.bouncycastle.operator.OperatorCreationException in project athenz by yahoo.
the class Crypto method loadPrivateKey.
public static PrivateKey loadPrivateKey(Reader reader, String pwd) throws CryptoException {
try (PEMParser pemReader = new PEMParser(reader)) {
PrivateKey privKey = null;
X9ECParameters ecParam = null;
Object pemObj = pemReader.readObject();
if (pemObj instanceof ASN1ObjectIdentifier) {
// make sure this is EC Parameter we're handling. In which case
// we'll store it and read the next object which should be our
// EC Private Key
ASN1ObjectIdentifier ecOID = (ASN1ObjectIdentifier) pemObj;
ecParam = ECNamedCurveTable.getByOID(ecOID);
if (ecParam == null) {
throw new PEMException("Unable to find EC Parameter for the given curve oid: " + ((ASN1ObjectIdentifier) pemObj).getId());
}
pemObj = pemReader.readObject();
} else if (pemObj instanceof X9ECParameters) {
ecParam = (X9ECParameters) pemObj;
pemObj = pemReader.readObject();
}
if (pemObj instanceof PEMKeyPair) {
PrivateKeyInfo pKeyInfo = ((PEMKeyPair) pemObj).getPrivateKeyInfo();
JcaPEMKeyConverter pemConverter = new JcaPEMKeyConverter();
privKey = pemConverter.getPrivateKey(pKeyInfo);
} else if (pemObj instanceof PKCS8EncryptedPrivateKeyInfo) {
PKCS8EncryptedPrivateKeyInfo pKeyInfo = (PKCS8EncryptedPrivateKeyInfo) pemObj;
if (pwd == null) {
throw new CryptoException("No password specified to decrypt encrypted private key");
}
// Decrypt the private key with the specified password
InputDecryptorProvider pkcs8Prov = new JceOpenSSLPKCS8DecryptorProviderBuilder().setProvider(BC_PROVIDER).build(pwd.toCharArray());
PrivateKeyInfo privateKeyInfo = pKeyInfo.decryptPrivateKeyInfo(pkcs8Prov);
JcaPEMKeyConverter pemConverter = new JcaPEMKeyConverter();
privKey = pemConverter.getPrivateKey(privateKeyInfo);
}
if (ecParam != null && ECDSA.equals(privKey.getAlgorithm())) {
ECParameterSpec ecSpec = new ECParameterSpec(ecParam.getCurve(), ecParam.getG(), ecParam.getN(), ecParam.getH(), ecParam.getSeed());
KeyFactory keyFactory = KeyFactory.getInstance(ECDSA, BC_PROVIDER);
ECPrivateKeySpec keySpec = new ECPrivateKeySpec(((BCECPrivateKey) privKey).getS(), ecSpec);
privKey = (PrivateKey) keyFactory.generatePrivate(keySpec);
}
return privKey;
} catch (PEMException e) {
LOG.error("loadPrivateKey: Caught PEMException, problem with format of key detected.");
throw new CryptoException(e);
} catch (NoSuchProviderException e) {
LOG.error("loadPrivateKey: Caught NoSuchProviderException, check to make sure the provider is loaded correctly.");
throw new CryptoException(e);
} catch (NoSuchAlgorithmException e) {
LOG.error("loadPrivateKey: Caught NoSuchAlgorithmException, check to make sure the algorithm is supported by the provider.");
throw new CryptoException(e);
} catch (InvalidKeySpecException e) {
LOG.error("loadPrivateKey: Caught InvalidKeySpecException, invalid key spec is being used.");
throw new CryptoException(e);
} catch (OperatorCreationException e) {
LOG.error("loadPrivateKey: Caught OperatorCreationException when creating JceOpenSSLPKCS8DecryptorProviderBuilder.");
throw new CryptoException(e);
} catch (PKCSException e) {
LOG.error("loadPrivateKey: Caught PKCSException when decrypting private key.");
throw new CryptoException(e);
} catch (IOException e) {
LOG.error("loadPrivateKey: Caught IOException, while trying to read key.");
throw new CryptoException(e);
}
}
use of org.bouncycastle.operator.OperatorCreationException in project pdfbox by apache.
the class CreateSignatureBase method sign.
/**
* SignatureInterface implementation.
*
* This method will be called from inside of the pdfbox and create the PKCS #7 signature.
* The given InputStream contains the bytes that are given by the byte range.
*
* This method is for internal use only.
*
* Use your favorite cryptographic library to implement PKCS #7 signature creation.
*
* @throws IOException
*/
@Override
public byte[] sign(InputStream content) throws IOException {
// cannot be done private (interface)
try {
List<Certificate> certList = new ArrayList<>();
certList.addAll(Arrays.asList(certificateChain));
Store certs = new JcaCertStore(certList);
CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
org.bouncycastle.asn1.x509.Certificate cert = org.bouncycastle.asn1.x509.Certificate.getInstance(certificateChain[0].getEncoded());
ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA256WithRSA").build(privateKey);
gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build()).build(sha1Signer, new X509CertificateHolder(cert)));
gen.addCertificates(certs);
CMSProcessableInputStream msg = new CMSProcessableInputStream(content);
CMSSignedData signedData = gen.generate(msg, false);
if (tsaUrl != null && tsaUrl.length() > 0) {
ValidationTimeStamp validation = new ValidationTimeStamp(tsaUrl);
signedData = validation.addSignedTimeStamp(signedData);
}
return signedData.getEncoded();
} catch (GeneralSecurityException | CMSException | OperatorCreationException e) {
throw new IOException(e);
}
}
use of org.bouncycastle.operator.OperatorCreationException in project pdfbox by apache.
the class ShowSignature method showSignature.
private void showSignature(String[] args) throws IOException, CertificateException, NoSuchAlgorithmException, NoSuchProviderException, TSPException {
if (args.length != 2) {
usage();
} else {
String password = args[0];
File infile = new File(args[1]);
try (PDDocument document = PDDocument.load(infile, password)) {
for (PDSignature sig : document.getSignatureDictionaries()) {
COSDictionary sigDict = sig.getCOSObject();
COSString contents = (COSString) sigDict.getDictionaryObject(COSName.CONTENTS);
// download the signed content
byte[] buf;
try (FileInputStream fis = new FileInputStream(infile)) {
buf = sig.getSignedContent(fis);
}
System.out.println("Signature found");
int[] byteRange = sig.getByteRange();
if (byteRange.length != 4) {
System.err.println("Signature byteRange must have 4 items");
} else {
long fileLen = infile.length();
long rangeMax = byteRange[2] + (long) byteRange[3];
// multiply content length with 2 (because it is in hex in the PDF) and add 2 for < and >
int contentLen = contents.getString().length() * 2 + 2;
if (fileLen != rangeMax || byteRange[0] != 0 || byteRange[1] + contentLen != byteRange[2]) {
// a false result doesn't necessarily mean that the PDF is a fake
// see this answer why:
// https://stackoverflow.com/a/48185913/535646
System.out.println("Signature does not cover whole document");
} else {
System.out.println("Signature covers whole document");
}
}
if (sig.getName() != null) {
System.out.println("Name: " + sig.getName());
}
if (sig.getSignDate() != null) {
System.out.println("Modified: " + sdf.format(sig.getSignDate().getTime()));
}
String subFilter = sig.getSubFilter();
if (subFilter != null) {
switch(subFilter) {
case "adbe.pkcs7.detached":
case "ETSI.CAdES.detached":
verifyPKCS7(buf, contents, sig);
// TODO check certificate chain, revocation lists, timestamp...
break;
case "adbe.pkcs7.sha1":
{
// example: PDFBOX-1452.pdf
byte[] certData = contents.getBytes();
CertificateFactory factory = CertificateFactory.getInstance("X.509");
ByteArrayInputStream certStream = new ByteArrayInputStream(certData);
Collection<? extends Certificate> certs = factory.generateCertificates(certStream);
System.out.println("certs=" + certs);
byte[] hash = MessageDigest.getInstance("SHA1").digest(buf);
verifyPKCS7(hash, contents, sig);
// TODO check certificate chain, revocation lists, timestamp...
break;
}
case "adbe.x509.rsa_sha1":
{
// example: PDFBOX-2693.pdf
COSString certString = (COSString) sigDict.getDictionaryObject(COSName.CERT);
if (certString == null) {
System.err.println("The /Cert certificate string is missing in the signature dictionary");
return;
}
byte[] certData = certString.getBytes();
CertificateFactory factory = CertificateFactory.getInstance("X.509");
ByteArrayInputStream certStream = new ByteArrayInputStream(certData);
Collection<? extends Certificate> certs = factory.generateCertificates(certStream);
System.out.println("certs=" + certs);
// TODO verify signature
break;
}
case "ETSI.RFC3161":
TimeStampToken timeStampToken = new TimeStampToken(new CMSSignedData(contents.getBytes()));
System.out.println("Time stamp gen time: " + timeStampToken.getTimeStampInfo().getGenTime());
System.out.println("Time stamp tsa name: " + timeStampToken.getTimeStampInfo().getTsa().getName());
CertificateFactory factory = CertificateFactory.getInstance("X.509");
ByteArrayInputStream certStream = new ByteArrayInputStream(contents.getBytes());
Collection<? extends Certificate> certs = factory.generateCertificates(certStream);
System.out.println("certs=" + certs);
// TODO verify signature
break;
default:
System.err.println("Unknown certificate type: " + subFilter);
break;
}
} else {
throw new IOException("Missing subfilter for cert dictionary");
}
}
analyseDSS(document);
} catch (CMSException | OperatorCreationException ex) {
throw new IOException(ex);
}
System.out.println("Analyzed: " + args[1]);
}
}
Aggregations