use of org.bouncycastle.asn1.cms.Attributes in project structr by structr.
the class CreateJarFileFunction method apply.
@Override
public Object apply(final ActionContext ctx, final Object caller, final Object[] sources) throws FrameworkException {
if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) {
if (sources[0] instanceof OutputStream) {
try {
final String algorithm = "SHA1";
final String signAlgorithm = "SHA1withRSA";
final String keygenAlgorithm = "RSA";
final String srngAlgorithm = "SHA1PRNG";
final JarOutputStream jos = new JarOutputStream((OutputStream) sources[0]);
final MessageDigest md = MessageDigest.getInstance(algorithm);
final Manifest manifest = new Manifest();
final Attributes mainAttributes = manifest.getMainAttributes();
final PrivateKey privateKey = getOrCreatePrivateKey(keygenAlgorithm, srngAlgorithm, signAlgorithm);
final X509Certificate cert = getOrCreateCertificate(keygenAlgorithm, srngAlgorithm, signAlgorithm);
System.out.println("This is the fingerprint of the keystore: " + hex(cert));
// if (false) {
//
// // this code loads an existing keystore
// final String keystorePath = StructrApp.getConfigurationValue("application.keystore.path", null);
// final String keystorePassword = StructrApp.getConfigurationValue("application.keystore.password", null);
//
// X509Certificate cert = null;
// PrivateKey privateKey = null;
//
// if (StringUtils.isNoneBlank(keystorePath, keystorePassword)) {
//
// try (final FileInputStream fis = new FileInputStream(keystorePath)) {
//
// final KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
//
// keystore.load(fis, keystorePassword.toCharArray());
//
// for (final Enumeration<String> aliases = keystore.aliases(); aliases.hasMoreElements();) {
//
// final String alias = aliases.nextElement();
//
// if (keystore.isCertificateEntry(alias)) {
//
// System.out.println("Using certificate entry " + alias);
// cert = (X509Certificate)keystore.getCertificate(alias);
//
// } else if (keystore.isKeyEntry(alias)) {
//
// System.out.println("Using private key entry " + alias);
// privateKey = (PrivateKey)keystore.getKey(alias, keystorePassword.toCharArray());
//
// }
// }
//
//
// } catch (Throwable t) {
//
// logger.warn("", t);
// }
// }
// }
// maximum compression
jos.setLevel(9);
// initialize manifest
mainAttributes.put(Attributes.Name.MANIFEST_VERSION, "1.0");
// add entries from scripting context
for (final Object source : sources) {
if (source != null && source instanceof NameAndContent) {
final NameAndContent content = (NameAndContent) source;
final JarEntry entry = new JarEntry(content.getName());
final byte[] data = content.getContent().getBytes("utf-8");
entry.setTime(System.currentTimeMillis());
// write JarEntry
jos.putNextEntry(entry);
jos.write(data);
jos.closeEntry();
jos.flush();
// update message digest with data
md.update(data);
// create new attribute with the entry's name
Attributes attr = manifest.getAttributes(entry.getName());
if (attr == null) {
attr = new Attributes();
manifest.getEntries().put(entry.getName(), attr);
}
// store SHA1-Digest for the new entry
attr.putValue(algorithm + "-Digest", new String(Base64.encode(md.digest()), "ASCII"));
}
}
// add manifest entry
jos.putNextEntry(new JarEntry(JarFile.MANIFEST_NAME));
manifest.write(jos);
// add signature entry
final byte[] signedData = getSignatureForManifest(manifest, algorithm);
jos.putNextEntry(new JarEntry("META-INF/CERT.SF"));
jos.write(signedData);
if (privateKey != null && cert != null) {
// add certificate entry
jos.putNextEntry(new JarEntry("META-INF/CERT." + privateKey.getAlgorithm()));
writeSignatureBlock(jos, algorithm, new CMSProcessableByteArray(signedData), cert, privateKey);
} else {
System.out.println("No certificate / key found, signinig disabled.");
}
// use finish() here to avoid an "already closed" exception later
jos.flush();
jos.finish();
} catch (Throwable t) {
logException(caller, t, sources);
}
} else {
logger.warn("First parameter of create_jar_file() must be an output stream. Parameters: {}", getParametersAsString(sources));
return "First parameter of create_jar_file() must be an output stream.";
}
} else {
logParameterError(caller, sources, ctx.isJavaScriptContext());
}
return "";
}
use of org.bouncycastle.asn1.cms.Attributes in project drill by apache.
the class WebServer method createHttpsConnector.
/**
* Create an HTTPS connector for given jetty server instance. If the admin has
* specified keystore/truststore settings they will be used else a self-signed
* certificate is generated and used.
* <p>
* This is a shameless copy of
* org.apache.drill.exec.server.rest.WebServer#createHttpsConnector(int, int, int).
* The two should be merged at some point. The primary issue is that the Drill
* version is tightly coupled to Drillbit configuration.
*
* @return Initialized {@link ServerConnector} for HTTPS connections.
* @throws Exception when unable to create HTTPS connector
*/
private ServerConnector createHttpsConnector(Config config) throws Exception {
LOG.info("Setting up HTTPS connector for web server");
final SslContextFactory sslContextFactory = new SslContextFactory();
// if (config.hasPath(ExecConstants.HTTP_KEYSTORE_PATH) &&
// !Strings.isNullOrEmpty(config.getString(ExecConstants.HTTP_KEYSTORE_PATH)))
// {
// LOG.info("Using configured SSL settings for web server");
// sslContextFactory.setKeyStorePath(config.getString(ExecConstants.HTTP_KEYSTORE_PATH));
// sslContextFactory.setKeyStorePassword(config.getString(ExecConstants.HTTP_KEYSTORE_PASSWORD));
//
// // TrustStore and TrustStore password are optional
// if (config.hasPath(ExecConstants.HTTP_TRUSTSTORE_PATH)) {
// sslContextFactory.setTrustStorePath(config.getString(ExecConstants.HTTP_TRUSTSTORE_PATH));
// if (config.hasPath(ExecConstants.HTTP_TRUSTSTORE_PASSWORD)) {
// sslContextFactory.setTrustStorePassword(config.getString(ExecConstants.HTTP_TRUSTSTORE_PASSWORD));
// }
// }
// } else {
LOG.info("Using generated self-signed SSL settings for web server");
final SecureRandom random = new SecureRandom();
// Generate a private-public key pair
final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(1024, random);
final KeyPair keyPair = keyPairGenerator.generateKeyPair();
final DateTime now = DateTime.now();
// Create builder for certificate attributes
final X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE).addRDN(BCStyle.OU, "Apache Drill (auth-generated)").addRDN(BCStyle.O, "Apache Software Foundation (auto-generated)").addRDN(BCStyle.CN, "Drill AM");
final Date notBefore = now.minusMinutes(1).toDate();
final Date notAfter = now.plusYears(5).toDate();
final BigInteger serialNumber = new BigInteger(128, random);
// Create a certificate valid for 5years from now.
final X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(// attributes
nameBuilder.build(), serialNumber, notBefore, notAfter, nameBuilder.build(), keyPair.getPublic());
// Sign the certificate using the private key
final ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(keyPair.getPrivate());
final X509Certificate certificate = new JcaX509CertificateConverter().getCertificate(certificateBuilder.build(contentSigner));
// Check the validity
certificate.checkValidity(now.toDate());
// Make sure the certificate is self-signed.
certificate.verify(certificate.getPublicKey());
// Generate a random password for keystore protection
final String keyStorePasswd = RandomStringUtils.random(20);
final KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(null, null);
keyStore.setKeyEntry("DrillAutoGeneratedCert", keyPair.getPrivate(), keyStorePasswd.toCharArray(), new java.security.cert.Certificate[] { certificate });
sslContextFactory.setKeyStore(keyStore);
sslContextFactory.setKeyStorePassword(keyStorePasswd);
// }
final HttpConfiguration httpsConfig = baseHttpConfig();
httpsConfig.addCustomizer(new SecureRequestCustomizer());
// SSL Connector
final ServerConnector sslConnector = new ServerConnector(jettyServer, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(httpsConfig));
sslConnector.setPort(config.getInt(DrillOnYarnConfig.HTTP_PORT));
return sslConnector;
}
use of org.bouncycastle.asn1.cms.Attributes in project pdfbox by apache.
the class ValidationTimeStamp method signTimeStamp.
/**
* Extend CMS Signer Information with the TimeStampToken into the unsigned Attributes.
*
* @param signer information about signer
* @return information about SignerInformation
* @throws IOException
*/
private SignerInformation signTimeStamp(SignerInformation signer) throws IOException {
AttributeTable unsignedAttributes = signer.getUnsignedAttributes();
ASN1EncodableVector vector = new ASN1EncodableVector();
if (unsignedAttributes != null) {
vector = unsignedAttributes.toASN1EncodableVector();
}
TimeStampToken timeStampToken = tsaClient.getTimeStampToken(new ByteArrayInputStream(signer.getSignature()));
byte[] token = timeStampToken.getEncoded();
ASN1ObjectIdentifier oid = PKCSObjectIdentifiers.id_aa_signatureTimeStampToken;
ASN1Encodable signatureTimeStamp = new Attribute(oid, new DERSet(ASN1Primitive.fromByteArray(token)));
vector.add(signatureTimeStamp);
Attributes signedAttributes = new Attributes(vector);
// see source code of replaceUnsignedAttributes
return SignerInformation.replaceUnsignedAttributes(signer, new AttributeTable(signedAttributes));
}
use of org.bouncycastle.asn1.cms.Attributes in project pdfbox by apache.
the class CertInformationCollector method addTimestampCerts.
/**
* Processes an embedded signed timestamp, that has been placed into a signature. The
* certificates and its chain(s) will be processed the same way as the signature itself.
*
* @param signerInformation of the signature, to get unsigned attributes from it.
* @throws IOException
* @throws CertificateProccessingException
*/
private void addTimestampCerts(SignerInformation signerInformation) throws IOException, CertificateProccessingException {
AttributeTable unsignedAttributes = signerInformation.getUnsignedAttributes();
if (unsignedAttributes == null) {
return;
}
Attribute tsAttribute = unsignedAttributes.get(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken);
if (tsAttribute == null) {
return;
}
ASN1Encodable obj0 = tsAttribute.getAttrValues().getObjectAt(0);
if (!(obj0 instanceof ASN1Object)) {
return;
}
ASN1Object tsSeq = (ASN1Object) obj0;
try {
CMSSignedData signedData = new CMSSignedData(tsSeq.getEncoded("DER"));
rootCertInfo.tsaCerts = new CertSignatureInformation();
processSignerStore(signedData, rootCertInfo.tsaCerts);
} catch (CMSException e) {
throw new IOException("Error parsing timestamp token", e);
}
}
Aggregations