List of usage examples for org.bouncycastle.cms DefaultSignedAttributeTableGenerator DefaultSignedAttributeTableGenerator
public DefaultSignedAttributeTableGenerator()
From source file:com.indivica.olis.Driver.java
License:Open Source License
public static String signData(String data) { X509Certificate cert = null;// w ww. j a v a 2s.c o m PrivateKey priv = null; KeyStore keystore = null; String pwd = "Olis2011"; String result = null; try { Security.addProvider(new BouncyCastleProvider()); keystore = KeyStore.getInstance("PKCS12", "SunJSSE"); // Load the keystore keystore.load(new FileInputStream(OscarProperties.getInstance().getProperty("olis_keystore")), pwd.toCharArray()); Enumeration e = keystore.aliases(); String name = ""; if (e != null) { while (e.hasMoreElements()) { String n = (String) e.nextElement(); if (keystore.isKeyEntry(n)) { name = n; } } } // Get the private key and the certificate priv = (PrivateKey) keystore.getKey(name, pwd.toCharArray()); cert = (X509Certificate) keystore.getCertificate(name); // I'm not sure if this is necessary Certificate[] certChain = keystore.getCertificateChain(name); ArrayList<Certificate> certList = new ArrayList<Certificate>(); certList.add(cert); CertStore certs = null; certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC"); // Encrypt data CMSSignedDataGenerator sgen = new CMSSignedDataGenerator(); // What digest algorithm i must use? SHA1? MD5? RSA?... DefaultSignedAttributeTableGenerator attributeGenerator = new DefaultSignedAttributeTableGenerator(); sgen.addSigner(priv, cert, CMSSignedDataGenerator.DIGEST_SHA1, attributeGenerator, null); // I'm not sure this is necessary sgen.addCertificatesAndCRLs(certs); // I think that the 2nd parameter need to be false (detached form) CMSSignedData csd = sgen.generate(new CMSProcessableByteArray(data.getBytes()), true, "BC"); byte[] signedData = csd.getEncoded(); byte[] signedDataB64 = Base64.encode(signedData); result = new String(signedDataB64); } catch (Exception e) { MiscUtils.getLogger().error("Can't sign HL7 message for OLIS", e); } return result; }
From source file:net.sf.keystore_explorer.crypto.signing.JarSigner.java
License:Open Source License
private static byte[] createSignatureBlock(byte[] toSign, PrivateKey privateKey, X509Certificate[] certificateChain, SignatureType signatureType, String tsaUrl, Provider provider) throws CryptoException { try {//from w ww . j a v a2 s. co m List<X509Certificate> certList = new ArrayList<X509Certificate>(); Collections.addAll(certList, certificateChain); DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder().setProvider("BC") .build(); JcaContentSignerBuilder csb = new JcaContentSignerBuilder(signatureType.jce()) .setSecureRandom(SecureRandom.getInstance("SHA1PRNG")); if (provider != null) { csb.setProvider(provider); } JcaSignerInfoGeneratorBuilder siGeneratorBuilder = new JcaSignerInfoGeneratorBuilder(digCalcProv); // remove cmsAlgorithmProtect for compatibility reasons SignerInfoGenerator sigGen = siGeneratorBuilder.build(csb.build(privateKey), certificateChain[0]); final CMSAttributeTableGenerator sAttrGen = sigGen.getSignedAttributeTableGenerator(); sigGen = new SignerInfoGenerator(sigGen, new DefaultSignedAttributeTableGenerator() { @Override public AttributeTable getAttributes(@SuppressWarnings("rawtypes") Map parameters) { AttributeTable ret = sAttrGen.getAttributes(parameters); return ret.remove(CMSAttributes.cmsAlgorithmProtect); } }, sigGen.getUnsignedAttributeTableGenerator()); CMSSignedDataGenerator dataGen = new CMSSignedDataGenerator(); dataGen.addSignerInfoGenerator(sigGen); dataGen.addCertificates(new JcaCertStore(certList)); CMSSignedData signedData = dataGen.generate(new CMSProcessableByteArray(toSign), true); // now let TSA time-stamp the signature if (tsaUrl != null && !tsaUrl.isEmpty()) { signedData = addTimestamp(tsaUrl, signedData); } return signedData.getEncoded(); } catch (Exception ex) { throw new CryptoException(res.getString("SignatureBlockCreationFailed.exception.message"), ex); } }
From source file:org.usrz.libs.crypto.utils.PKCS7.java
License:Apache License
/** * Prepare a detached <code>PKCS7</code> signature. * * @param privateKey The private key to use for signing * @param certificate The certificate associated with the private key. * @param authorities An optional list of certificate authorities to include. * @param data The {@linkplain Hash hashing algorithm} to use for signing. * @param data The binary data to sign.// w ww. j av a 2 s. c o m * @return The <code>PKCS7</code> as a byte array. * @throws SignatureException If there was a problem generating the signature. */ public static byte[] sign(final PrivateKey privateKey, final X509Certificate certificate, final List<X509Certificate> authorities, final Hash hash, final byte[] data) throws SignatureException { try { final String signatureAlgorithm = CryptoUtils.getSignatureAlgorithm(privateKey, hash); final ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm).build(privateKey); final CMSSignedDataGenerator generator = new CMSSignedDataGenerator(); generator.addSignerInfoGenerator( new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build()) .setSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator()) .build(signer, certificate)); final Set<Certificate> certificates = new HashSet<>(); if (authorities != null) { for (Certificate authority : authorities) certificates.add(authority); } certificates.add(certificate); generator.addCertificates(new JcaCertStore(certificates)); final CMSTypedData cmsData = new CMSProcessableByteArray(data); final CMSSignedData signeddata = generator.generate(cmsData, false); return signeddata.getEncoded(); } catch (Exception exception) { throw new SignatureException("Signature could not be generated", exception); } }
From source file:org.votingsystem.signature.util.PDFContentSigner.java
License:Open Source License
public CMSSignedData genSignedData(byte[] signatureHash, CMSAttributeTableGenerator unsAttr) throws Exception { CMSProcessable content = new CMSProcessableByteArray(signatureHash); ByteArrayOutputStream out = null; if (content != null) { out = new ByteArrayOutputStream(); content.write(out);// w ww. ja v a2 s .c o m out.close(); } ByteArrayInputStream bais = new ByteArrayInputStream(out.toByteArray()); MessageDigest softwareDigestEngine = MessageDigest.getInstance(signatureDigestAlg); int bytesRead; byte[] dataBuffer = new byte[4096]; while ((bytesRead = bais.read(dataBuffer)) >= 0) { softwareDigestEngine.update(dataBuffer, 0, bytesRead); } byte[] hash = softwareDigestEngine.digest(); CertStore certsAndCRLs = CertStore.getInstance(CERT_STORE_TYPE, new CollectionCertStoreParameters(Arrays.asList(signerCertChain)), ContextVS.PROVIDER); addCertificatesAndCRLs(certsAndCRLs); CMSAttributeTableGenerator sAttr = new DefaultSignedAttributeTableGenerator(); ASN1ObjectIdentifier contentTypeOID = new ASN1ObjectIdentifier(CMSSignedGenerator.DATA); Map parameters = getBaseParameters(contentTypeOID, new AlgorithmIdentifier(new DERObjectIdentifier(pdfDigestObjectIdentifier), new DERNull()), hash); AttributeTable attributeTable = sAttr.getAttributes(Collections.unmodifiableMap(parameters)); //String signatureHashStr = new String(Base64.encode(signatureHash)); JcaSimpleSignerInfoGeneratorBuilder jcaSignerInfoGeneratorBuilder = new JcaSimpleSignerInfoGeneratorBuilder(); jcaSignerInfoGeneratorBuilder = jcaSignerInfoGeneratorBuilder.setProvider(ContextVS.PROVIDER); jcaSignerInfoGeneratorBuilder.setSignedAttributeGenerator(attributeTable); jcaSignerInfoGeneratorBuilder.setUnsignedAttributeGenerator(unsAttr); SignerInfoGenerator signerInfoGenerator = jcaSignerInfoGeneratorBuilder.build(signatureMechanism, privateKey, userCert); SignerInfo signerInfo = signerInfoGenerator.generate(contentTypeOID); List<SignerInfo> signerInfoList = new ArrayList<SignerInfo>(); signerInfoList.add(signerInfo); log.info(" -- userCert: " + userCert.getSubjectDN().getName()); CMSSignedData signedData = getCMSSignedData(CMSSignedGenerator.DATA, content, true, CMSUtils.getProvider("BC"), true, signerInfoList); return signedData; }
From source file:org.xipki.pki.scep.message.NextCaMessage.java
License:Open Source License
public ContentInfo encode(final PrivateKey signingKey, final X509Certificate signerCert, final X509Certificate[] cmsCertSet) throws MessageEncodingException { ParamUtil.requireNonNull("signingKey", signingKey); ParamUtil.requireNonNull("signerCert", signerCert); try {//from w w w. ja v a2s . com byte[] degenratedSignedDataBytes; try { CMSSignedDataGenerator degenerateSignedData = new CMSSignedDataGenerator(); degenerateSignedData.addCertificate(new X509CertificateHolder(caCert.getEncoded())); if (raCerts != null && !raCerts.isEmpty()) { for (X509Certificate m : raCerts) { degenerateSignedData.addCertificate(new X509CertificateHolder(m.getEncoded())); } } degenratedSignedDataBytes = degenerateSignedData.generate(new CMSAbsentContent()).getEncoded(); } catch (CertificateEncodingException ex) { throw new MessageEncodingException(ex.getMessage(), ex); } CMSSignedDataGenerator generator = new CMSSignedDataGenerator(); // I don't known which hash algorithm is supported by the client, use SHA-1 String signatureAlgo = getSignatureAlgorithm(signingKey, ScepHashAlgoType.SHA1); ContentSigner signer = new JcaContentSignerBuilder(signatureAlgo).build(signingKey); // signerInfo JcaSignerInfoGeneratorBuilder signerInfoBuilder = new JcaSignerInfoGeneratorBuilder( new BcDigestCalculatorProvider()); signerInfoBuilder.setSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator()); SignerInfoGenerator signerInfo = signerInfoBuilder.build(signer, signerCert); generator.addSignerInfoGenerator(signerInfo); CMSTypedData cmsContent = new CMSProcessableByteArray(CMSObjectIdentifiers.signedData, degenratedSignedDataBytes); // certificateSet ScepUtil.addCmsCertSet(generator, cmsCertSet); return generator.generate(cmsContent, true).toASN1Structure(); } catch (CMSException ex) { throw new MessageEncodingException(ex); } catch (CertificateEncodingException ex) { throw new MessageEncodingException(ex); } catch (IOException ex) { throw new MessageEncodingException(ex); } catch (OperatorCreationException ex) { throw new MessageEncodingException(ex); } }