List of usage examples for org.bouncycastle.operator.jcajce JcaContentSignerBuilder JcaContentSignerBuilder
public JcaContentSignerBuilder(String signatureAlgorithm)
From source file:assinaBc.java
CMSSignedDataGenerator setUpProvider(final KeyStore keystore) throws Exception { Security.addProvider(new BouncyCastleProvider()); Certificate[] certchain = (Certificate[]) keystore.getCertificateChain(KEY_ALIAS_IN_KEYSTORE); final List<Certificate> certlist = new ArrayList<>(); for (int i = 0, length = certchain == null ? 0 : certchain.length; i < length; i++) { certlist.add(certchain[i]);//from w w w. ja va 2 s . c o m } Store certstore = new JcaCertStore(certlist); Certificate cert = keystore.getCertificate(KEY_ALIAS_IN_KEYSTORE); ContentSigner signer = new JcaContentSignerBuilder(SIGNATUREALGO).setProvider("BC") .build((PrivateKey) (keystore.getKey(KEY_ALIAS_IN_KEYSTORE, KEYSTORE_PASSWORD.toCharArray()))); CMSSignedDataGenerator generator = new CMSSignedDataGenerator(); generator.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder( new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()).build(signer, (X509Certificate) cert)); generator.addCertificates(certstore); return generator; }
From source file:CreateSignatureBase.java
License:Apache License
/** * SignatureInterface implementation.//ww w . j ava2 s .c om * * 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. <-- TODO this method should be private * * Use your favorite cryptographic library to implement PKCS #7 signature creation. */ @Override public byte[] sign(InputStream content) throws IOException { try { List<Certificate> certList = new ArrayList<Certificate>(); certList.add(certificate); Store certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); org.bouncycastle.asn1.x509.Certificate cert = org.bouncycastle.asn1.x509.Certificate .getInstance(ASN1Primitive.fromByteArray(certificate.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 (tsaClient != null) { signedData = signTimeStamps(signedData); } return signedData.getEncoded(); } catch (GeneralSecurityException e) { throw new IOException(e); } catch (CMSException e) { throw new IOException(e); } catch (TSPException e) { throw new IOException(e); } catch (OperatorCreationException e) { throw new IOException(e); } }
From source file:CA.java
License:Apache License
private static void generateCertificateAuthorityCerts() throws Exception { Properties p = readProperties(); // Generate CA key pair KeyPairGenerator keyGen = null; String algorithm = p.getProperty("jcsi.ca.keyAlg", "DSA"); int keyLen = Integer.parseInt(p.getProperty("jcsi.ca.keyLength", "512")); keyGen = KeyPairGenerator.getInstance(algorithm, "BC"); SecureRandom random = new SecureRandom(); keyGen.initialize(keyLen, random);//from www. j av a 2 s .c o m KeyPair keys = keyGen.generateKeyPair(); PublicKey publicKey = keys.getPublic(); PrivateKey privKey = keys.getPrivate(); // The key used to sign our Certificate. String issuerDN = p.getProperty("jcsi.ca.issuerDN"); long validDays = Integer.parseInt(p.getProperty("jcsi.ca.validityPeriod")); String signerAlgorithm = p.getProperty("jcsi.ca.sigAlg", "SHA1withDSA"); // Generate root certificate ContentSigner sigGen = new JcaContentSignerBuilder(signerAlgorithm).setProvider("BC").build(privKey); X500Principal issuer = new X500Principal(issuerDN); X500Principal subject = issuer; // Self signed. long time = System.currentTimeMillis(); BigInteger serial = BigInteger.valueOf(time); Date notBefore = new Date(time - 50000); Date notAfter = new Date(time + validDays * 86400000L); Certificate rootCert = build(sigGen, issuer, serial, notBefore, notAfter, subject, publicKey); //Write Private key and Certificate to file. writePrivateKey(privKey, p, random); writeRootCertificate(rootCert, p); // // Pasword Protect the private key in preparate to write to file. // String password = p.getProperty("jcsi.ca.privKey.password", "changeit"); // byte[] salt = "salt and pepper shakers &*@".getBytes(); // int iterationCount = 2048; // PBEKeySpec pbeSpec = new PBEKeySpec(password.toCharArray(), salt, iterationCount); // Cipher cipher = null; // SecretKeyFactory skf = null; // byte [] wrappedPrivKey = null; // cipher = Cipher.getInstance("PBEWithSHA1AndDES", "BC"); // skf = SecretKeyFactory.getInstance("PBEWithSHA1AndDES", "BC"); // cipher.init(Cipher.WRAP_MODE, skf.generateSecret(pbeSpec)); // wrappedPrivKey = cipher.wrap(privKey); // // String directory = p.getProperty("jcsi.ca.key.dir", "."); // // String keyFileName = p.getProperty("jcsi.ca.privKey", "private.key"); // String certFileName = p.getProperty("jcsi.ca.cert", "user.cert"); // // File keyFile = new File(directory + "/" + keyFileName); // keyFile.canWrite(); // File certFile = new File (directory + "/" + certFileName); // certFile.canWrite(); // writeFile(certFile, rootCert.getEncoded()); // writeFile(keyFile, wrappedPrivKey); }
From source file:CA.java
License:Apache License
private static ContentSigner getContentSigner(Properties p) throws Exception { String signerAlgorithm = p.getProperty("jcsi.ca.sigAlg", "SHA1withDSA"); return new JcaContentSignerBuilder(signerAlgorithm).setProvider("BC").build(readPrivateKey(p)); }
From source file:AAModulePackage.ACHelper.java
public static X509AttributeCertificateHolder generateAttributeCertificate(X509CertificateHolder issuerCert, X509CertificateHolder associatedCert, PrivateKey pk, String role, String record_id, String record_subject, String[] record_types, String[] actions_taken) { //Set up the validity period. Date startDate = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000); Date endDate = new Date(System.currentTimeMillis() + 365 * 24 * 60 * 60 * 1000); //AttributeCertificateHolder is a wrapper class for AttributeCertificates, courtesy of the Legion of Bouncy Castle. AttributeCertificateIssuer certIssuer = new AttributeCertificateIssuer(issuerCert.getSubject()); /*/*from w ww . j av a2 s. c o m*/ Please note the distinction between AttributeCertificateHolder which appears to be the Entity in possession of the certificate, while X509AttributeCertificateHolder is a wrapper class for the actual certificate itself. */ AttributeCertificateHolder holder = new AttributeCertificateHolder(associatedCert); X509v2AttributeCertificateBuilder builder = new X509v2AttributeCertificateBuilder(holder, certIssuer, BigInteger.valueOf(System.currentTimeMillis()), startDate, endDate); builder.addAttribute(NewAttributeIdentifiers.role, new DERGeneralString(role)); builder.addAttribute(NewAttributeIdentifiers.record_id, new DERGeneralString(record_id)); builder.addAttribute(NewAttributeIdentifiers.record_subject, new DERGeneralString(record_subject)); builder.addAttribute(NewAttributeIdentifiers.time_stamp, new DERGeneralizedTime(new Date())); //record_types ArrayList<ASN1Encodable> rts = new ArrayList(); for (String s : record_types) { rts.add(new DERGeneralString(s)); } ASN1Encodable[] recTypes = rts.toArray(new DERGeneralString[rts.size()]); builder.addAttribute(NewAttributeIdentifiers.record_type, recTypes); //actions_taken ArrayList<ASN1Encodable> acts = new ArrayList(); for (String s : actions_taken) { acts.add(new DERGeneralString(s)); } ASN1Encodable[] actionsTaken = acts.toArray(new DERGeneralString[acts.size()]); builder.addAttribute(NewAttributeIdentifiers.actions_taken, actionsTaken); //Build the certificate X509AttributeCertificateHolder attrCert = null; try { //builds the attribute certificate, and signs it with the owner's private key. attrCert = builder .build(new JcaContentSignerBuilder("SHA256withRSAEncryption").setProvider("BC").build(pk)); } catch (OperatorCreationException e) { e.printStackTrace(); } System.out.println("ATTRIBUTE CERTIFICATE Successfully generated."); return attrCert; }
From source file:at.asitplus.regkassen.core.modules.signature.rawsignatureprovider.NEVER_USE_IN_A_REAL_SYSTEM_SoftwareCertificateOpenSystemSignatureModule.java
License:Apache License
public void intialise() { try {/* w ww . j av a 2s.co m*/ //create random demonstration ECC keys final KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC"); kpg.initialize(256); //256 bit ECDSA key //create a key pair for the demo Certificate Authority final KeyPair caKeyPair = kpg.generateKeyPair(); //create a key pair for the signature certificate, which is going to be used to sign the receipts final KeyPair signingKeyPair = kpg.generateKeyPair(); //get references to private keys for the CA and the signing key final PrivateKey caKey = caKeyPair.getPrivate(); signingKey = signingKeyPair.getPrivate(); //create CA certificate and add it to the certificate chain //NOTE: DO NEVER EVER USE IN A REAL CASHBOX, THIS IS JUST FOR DEMONSTRATION PURPOSES //NOTE: these certificates have random values, just for the demonstration purposes here //However, for testing purposes the most important feature is the EC256 Signing Key, since this is required //by the RK Suite final X509v3CertificateBuilder caBuilder = new X509v3CertificateBuilder(new X500Name("CN=RegKassa ZDA"), BigInteger.valueOf(new SecureRandom().nextLong()), new Date(System.currentTimeMillis() - 10000), new Date(System.currentTimeMillis() + 24L * 3600 * 1000), new X500Name("CN=RegKassa CA"), SubjectPublicKeyInfo.getInstance(caKeyPair.getPublic().getEncoded())); caBuilder.addExtension(X509Extension.basicConstraints, true, new BasicConstraints(false)); caBuilder.addExtension(X509Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature)); final X509CertificateHolder caHolder = caBuilder .build(new JcaContentSignerBuilder("SHA256withECDSA").setProvider("BC").build(caKey)); final X509Certificate caCertificate = new JcaX509CertificateConverter().setProvider("BC") .getCertificate(caHolder); certificateChain = new ArrayList<java.security.cert.Certificate>(); certificateChain.add(caCertificate); //create signing cert final long serialNumberCertificate = new SecureRandom().nextLong(); if (!closedSystemSignatureDevice) { serialNumberOrKeyId = Long.toHexString(serialNumberCertificate); } final X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder( new X500Name("CN=RegKassa CA"), BigInteger.valueOf(Math.abs(serialNumberCertificate)), new Date(System.currentTimeMillis() - 10000), new Date(System.currentTimeMillis() + 24L * 3600 * 1000), new X500Name("CN=Signing certificate"), SubjectPublicKeyInfo.getInstance(signingKeyPair.getPublic().getEncoded())); certBuilder.addExtension(X509Extension.basicConstraints, true, new BasicConstraints(false)); certBuilder.addExtension(X509Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature)); final X509CertificateHolder certHolder = certBuilder .build(new JcaContentSignerBuilder("SHA256withECDSA").setProvider("BC").build(caKey)); signingCertificate = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certHolder); } catch (final NoSuchAlgorithmException e) { e.printStackTrace(); } catch (final OperatorCreationException e) { e.printStackTrace(); } catch (final CertIOException e) { e.printStackTrace(); } catch (final CertificateException e) { e.printStackTrace(); } }
From source file:ataraxis.crypt.UBERKeyStoreHandlerTest.java
License:Open Source License
public static X509Certificate generateX509V3Cert(KeyPair keyPair) throws Exception { X509v1CertificateBuilder certBldr = new JcaX509v1CertificateBuilder(new X500Name("CN=Root"), BigInteger.valueOf(1), new Date(System.currentTimeMillis()), new Date(System.currentTimeMillis() + 1000 * 3600 * 24), new X500Name("CN=Root"), keyPair.getPublic());//from www.ja v a 2 s . c o m ContentSigner signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC") .build(keyPair.getPrivate()); return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certBldr.build(signer)); }
From source file:be.e_contract.mycarenet.certra.CertRASession.java
License:Open Source License
public byte[] generateCSR(X500Name name) throws OperatorCreationException, IOException { PKCS10CertificationRequestBuilder csrBuilder = new JcaPKCS10CertificationRequestBuilder(name, this.publicKey); JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder("SHA256withRSA"); ContentSigner signer = csBuilder.build(this.privateKey); PKCS10CertificationRequest csr = csrBuilder.build(signer); return csr.getEncoded(); }
From source file:be.e_contract.mycarenet.certra.cms.CMSSigner.java
License:Open Source License
private byte[] sign(byte[] data) throws SignatureException { CMSSignedDataGenerator cmsSignedDataGenerator = new CMSSignedDataGenerator(); try {/*from w w w . j a v a 2 s . c o m*/ ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256withRSA").build(this.privateKey); cmsSignedDataGenerator.addSignerInfoGenerator( new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder() .setProvider(BouncyCastleProvider.PROVIDER_NAME).build()).build(contentSigner, this.certificateChain.get(0))); for (X509Certificate certificate : this.certificateChain) { cmsSignedDataGenerator.addCertificate(new X509CertificateHolder(certificate.getEncoded())); } CMSTypedData cmsTypedData = new CMSProcessableByteArray(data); CMSSignedData cmsSignedData = cmsSignedDataGenerator.generate(cmsTypedData, true); return cmsSignedData.getEncoded(); } catch (Exception e) { throw new SignatureException(e); } }
From source file:be.fedict.trust.test.PKITestUtils.java
License:Open Source License
public static OCSPResp createOcspResp(X509Certificate certificate, boolean revoked, X509Certificate issuerCertificate, X509Certificate ocspResponderCertificate, PrivateKey ocspResponderPrivateKey, String signatureAlgorithm) throws Exception { // request// ww w . jav a 2 s .com OCSPReqBuilder ocspReqBuilder = new OCSPReqBuilder(); DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder() .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(); CertificateID certId = new CertificateID(digCalcProv.get(CertificateID.HASH_SHA1), new JcaX509CertificateHolder(issuerCertificate), certificate.getSerialNumber()); ocspReqBuilder.addRequest(certId); OCSPReq ocspReq = ocspReqBuilder.build(); BasicOCSPRespBuilder basicOCSPRespBuilder = new JcaBasicOCSPRespBuilder( ocspResponderCertificate.getPublicKey(), digCalcProv.get(CertificateID.HASH_SHA1)); // request processing Req[] requestList = ocspReq.getRequestList(); for (Req ocspRequest : requestList) { CertificateID certificateID = ocspRequest.getCertID(); CertificateStatus certificateStatus; if (revoked) { certificateStatus = new RevokedStatus(new Date(), CRLReason.unspecified); } else { certificateStatus = CertificateStatus.GOOD; } basicOCSPRespBuilder.addResponse(certificateID, certificateStatus); } // basic response generation X509CertificateHolder[] chain = null; if (!ocspResponderCertificate.equals(issuerCertificate)) { chain = new X509CertificateHolder[] { new X509CertificateHolder(ocspResponderCertificate.getEncoded()), new X509CertificateHolder(issuerCertificate.getEncoded()) }; } ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithm) .build(ocspResponderPrivateKey); BasicOCSPResp basicOCSPResp = basicOCSPRespBuilder.build(contentSigner, chain, new Date()); // response generation OCSPRespBuilder ocspRespBuilder = new OCSPRespBuilder(); OCSPResp ocspResp = ocspRespBuilder.build(OCSPRespBuilder.SUCCESSFUL, basicOCSPResp); return ocspResp; }