List of usage examples for java.security KeyPair getPrivate
public PrivateKey getPrivate()
From source file:org.ejbca.core.model.ca.catoken.CATokenContainerImpl.java
/** * Method that generates the keys that will be used by the CAToken. * The method can be used to generate keys for an initial CA token or to renew Certificate signing keys. * If setstatustowaiting is true and you generate new keys, the new keys will be available as SecConst.CAKEYPURPOSE_CERTSIGN. * If setstatustowaiting is false and you generate new keys, the new keys will be available as SecConst.CAKEYPURPOSE_CERTSIGN_NEXT. * //w ww . j a v a 2s .co m * @param authenticationCode the password used to encrypt the keystore, later needed to activate CA Token * @param renew flag indicating if the keys are renewed instead of created fresh. Renewing keys does not * create new encryption keys, since this would make it impossible to decrypt old stuff. * @param activate flag indicating if the new keys should be activated immediately or or they should be added as "next" signing key. * Using true here makes it possible to generate certificate renewal requests for external CAs still using the old keys until the response is received. */ public void generateKeys(final String authenticationCode, final boolean renew, final boolean activate) throws Exception { if (log.isTraceEnabled()) { log.trace(">generateKeys: " + (authenticationCode == null ? "null" : "hidden") + ", renew=" + renew + ", activate=" + activate); } CATokenInfo catokeninfo = getCATokenInfo(); // First we start by setting a new sequence for our new keys String oldSequence = getKeySequence(); log.debug("Current sequence: " + oldSequence); String newSequence = StringTools.incrementKeySequence(getCATokenInfo().getKeySequenceFormat(), oldSequence); // We store the sequence permanently in the object last, when we know everything went well // If we don't give an authentication code, perhaps we have autoactivation enabled char[] authCode = getAuthCodeOrAutoactivationPin(authenticationCode); String tokentype = null; // Then we can move on to actually generating the keys if (catokeninfo instanceof SoftCATokenInfo) { // If we have an existing soft keystore verify that the password is correct checkSoftKeystorePassword(authenticationCode); SoftCATokenInfo info = (SoftCATokenInfo) catokeninfo; Properties properties = getProperties(); PublicKey pubEnc = null; PrivateKey privEnc = null; PublicKey previousPubSign = null; PrivateKey previousPrivSign = null; PublicKey oldPreviousPubSign = null; PrivateKey oldPreviousPrivSign = null; if (!renew) { log.debug("We are generating initial keys."); // Generate encryption keys. // Encryption keys must be RSA still KeyPair enckeys = KeyTools.genKeys(info.getEncKeySpec(), info.getEncKeyAlgorithm()); pubEnc = enckeys.getPublic(); privEnc = enckeys.getPrivate(); } else { log.debug("We are renewing keys."); // Get the already existing encryption and signature keys ICAToken token = getCAToken(); pubEnc = token.getPublicKey(SecConst.CAKEYPURPOSE_KEYENCRYPT); privEnc = token.getPrivateKey(SecConst.CAKEYPURPOSE_KEYENCRYPT); previousPubSign = token.getPublicKey(SecConst.CAKEYPURPOSE_CERTSIGN); previousPrivSign = token.getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN); oldPreviousPubSign = token.getPublicKey(SecConst.CAKEYPURPOSE_CERTSIGN_PREVIOUS); oldPreviousPrivSign = token.getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN_PREVIOUS); } // As first choice we check if the used have specified which type of key should be generated, this can be different from the currently used key // If the user did not specify this, we try to generate a key with the same specification as the currently used key. String keyspec = info.getSignKeySpec(); // can be "unknown" if (StringUtils.equals(keyspec, AlgorithmTools.KEYSPEC_UNKNOWN)) { keyspec = null; } AlgorithmParameterSpec paramspec = KeyTools.getKeyGenSpec(previousPubSign); if (log.isDebugEnabled()) { if (keyspec != null) { log.debug("Generating new Soft key with specified spec " + keyspec + " with label " + SoftCAToken.PRIVATESIGNKEYALIAS); } else { int keySize = KeyTools.getKeyLength(previousPubSign); String alg = previousPubSign.getAlgorithm(); log.debug("Generating new Soft " + alg + " key with spec " + paramspec + " (size=" + keySize + ") with label " + SoftCAToken.PRIVATESIGNKEYALIAS); } } // Generate signature keys. KeyPair newsignkeys = KeyTools.genKeys(keyspec, paramspec, info.getSignKeyAlgorithm()); // Create the new keystore and add the new signature keys KeyStore keystore = KeyStore.getInstance("PKCS12", "BC"); keystore.load(null, null); // PLay with aliases depending on if we activate the new key or not String newSignKeyAlias = SoftCAToken.PRIVATESIGNKEYALIAS; String previousSignKeyAlias = SoftCAToken.PREVIOUSPRIVATESIGNKEYALIAS; if (!activate) { // If the new keys are not activated we must still use the old key as active signing key (PRIVATESIGNKEYALIAS) newSignKeyAlias = SoftCAToken.NEXTPRIVATESIGNKEYALIAS; previousSignKeyAlias = SoftCAToken.PRIVATESIGNKEYALIAS; } log.debug("Setting newsignkeys as " + newSignKeyAlias + " in soft CA token."); Certificate[] certchain = new Certificate[1]; // generate dummy certificate String sigAlg = (String) AlgorithmTools.getSignatureAlgorithms(newsignkeys.getPublic()).iterator() .next(); certchain[0] = CertTools.genSelfCert("CN=dummy", 36500, null, newsignkeys.getPrivate(), newsignkeys.getPublic(), sigAlg, true); keystore.setKeyEntry(newSignKeyAlias, newsignkeys.getPrivate(), null, certchain); if (!activate) { log.debug("Set next sequence: " + newSequence); properties.setProperty(ICAToken.NEXT_SEQUENCE_PROPERTY, newSequence); log.debug("Set nextCertSignKey: " + newSignKeyAlias); properties.setProperty(KeyStrings.CAKEYPURPOSE_CERTSIGN_STRING_NEXT, newSignKeyAlias); } // If we have an old key (i.e. generating new keys), we will store the old one as "previous" if (previousPrivSign != null) { log.debug("Setting previousPrivSign as " + previousSignKeyAlias + " in soft CA token."); sigAlg = (String) AlgorithmTools.getSignatureAlgorithms(previousPubSign).iterator().next(); certchain[0] = CertTools.genSelfCert("CN=dummy2", 36500, null, previousPrivSign, previousPubSign, sigAlg, true); keystore.setKeyEntry(previousSignKeyAlias, previousPrivSign, null, certchain); // Now this keystore should have this previous key if (activate) { // This key pair is now moved down to previous sign key properties.setProperty(KeyStrings.CAKEYPURPOSE_CERTSIGN_STRING_PREVIOUS, previousSignKeyAlias); // Set previous sequence so we can create link certificates log.debug("Set previous sequence : " + oldSequence); properties.setProperty(ICAToken.PREVIOUS_SEQUENCE_PROPERTY, oldSequence); } else { // If we have an old previous key and we are not activating the new key, we will keep this one as "previous" // If the new keys are activate the old previous keys are trashed and replaced by the old active signature key String prevProp = properties.getProperty(KeyStrings.CAKEYPURPOSE_CERTSIGN_STRING_PREVIOUS); // If we don't have a previous key don't try to add it if ((oldPreviousPrivSign != null) && (prevProp != null)) { log.debug("Setting old previousprivatesignkeyalias as " + SoftCAToken.PREVIOUSPRIVATESIGNKEYALIAS + " in soft CA token."); sigAlg = (String) AlgorithmTools.getSignatureAlgorithms(oldPreviousPubSign).iterator() .next(); certchain[0] = CertTools.genSelfCert("CN=dummy3", 36500, null, oldPreviousPrivSign, oldPreviousPubSign, sigAlg, true); keystore.setKeyEntry(SoftCAToken.PREVIOUSPRIVATESIGNKEYALIAS, oldPreviousPrivSign, null, certchain); properties.setProperty(KeyStrings.CAKEYPURPOSE_CERTSIGN_STRING_PREVIOUS, SoftCAToken.PREVIOUSPRIVATESIGNKEYALIAS); } else { log.debug("No previousprivatesignkeyalias exists, not setting any previous key."); } } } // Finally install the old encryption/decryption keys as well sigAlg = (String) AlgorithmTools.getSignatureAlgorithms(pubEnc).iterator().next(); certchain[0] = CertTools.genSelfCert("CN=dummy2", 36500, null, privEnc, pubEnc, sigAlg, true); keystore.setKeyEntry(SoftCAToken.PRIVATEDECKEYALIAS, privEnc, null, certchain); storeSoftKeyStore(authCode, info, properties, keystore); tokentype = "Soft"; // for logging } else if (catokeninfo instanceof HardCATokenInfo) { ICAToken token = getCAToken(); if (token instanceof PKCS11CAToken) { Properties properties = getProperties(); PublicKey pubK = token.getPublicKey(SecConst.CAKEYPURPOSE_CERTSIGN); String keyLabel = token.getKeyLabel(SecConst.CAKEYPURPOSE_CERTSIGN); log.debug("Old key label is: " + keyLabel); String crlKeyLabel = token.getKeyLabel(SecConst.CAKEYPURPOSE_CRLSIGN); // The key label to use for the new key // Remove the old sequence from the end of the key label and replace it with the // new label. If no label was present just concatenate the new label String newKeyLabel = StringUtils.removeEnd(keyLabel, oldSequence) + newSequence; log.debug("New key label is: " + newKeyLabel); final KeyStore.PasswordProtection pwp = new KeyStore.PasswordProtection(authCode); // As first choice we check if the used have specified which type of key should be generated, this can be different from the currently used key // If the user did not specify this, we try to generate a key with the same specification as the currently used key. String keyspec = properties.getProperty(ICAToken.KEYSPEC_PROPERTY); // can be null, and that is ok AlgorithmParameterSpec paramspec = KeyTools.getKeyGenSpec(pubK); if (log.isDebugEnabled()) { String sharedLibrary = properties.getProperty(PKCS11CAToken.SHLIB_LABEL_KEY); String slot = properties.getProperty(PKCS11CAToken.SLOT_LABEL_KEY); String attributesFile = properties.getProperty(PKCS11CAToken.ATTRIB_LABEL_KEY); if (keyspec != null) { log.debug("Generating new PKCS#11 key with specified spec " + keyspec + " with label " + newKeyLabel + ", on slot " + slot + ", using sharedLibrary " + sharedLibrary + ", and attributesFile " + attributesFile); } else { int keySize = KeyTools.getKeyLength(pubK); String alg = pubK.getAlgorithm(); log.debug("Generating new PKCS#11 " + alg + " key with spec " + paramspec + " (size=" + keySize + ") with label " + newKeyLabel + ", on slot " + slot + ", using sharedLibrary " + sharedLibrary + ", and attributesFile " + attributesFile); } } KeyStoreContainer cont = KeyStoreContainerFactory .getInstance(KeyStoreContainer.KEYSTORE_TYPE_PKCS11, token.getProvider(), pwp); cont.setPassPhraseLoadSave(authCode); if (keyspec != null) { log.debug("Generating from string keyspec: " + keyspec); cont.generate(keyspec, newKeyLabel); } else { log.debug("Generating from AlgorithmParameterSpec: " + paramspec); cont.generate(paramspec, newKeyLabel); } // Set properties so that we will start using the new key, or not, depending on the activate argument KeyStrings kstr = new KeyStrings(properties); String certsignkeystr = kstr.getKey(SecConst.CAKEYPURPOSE_CERTSIGN); log.debug("CAKEYPURPOSE_CERTSIGN keystring is: " + certsignkeystr); String crlsignkeystr = kstr.getKey(SecConst.CAKEYPURPOSE_CRLSIGN); log.debug("CAKEYPURPOSE_CRLSIGN keystring is: " + crlsignkeystr); if (!activate) { // If the new keys are not activated we must still use the old key as active signing key (PRIVATESIGNKEYALIAS) log.debug("Set nextCertSignKey: " + newKeyLabel); properties.setProperty(KeyStrings.CAKEYPURPOSE_CERTSIGN_STRING_NEXT, newKeyLabel); log.debug("Set next sequence: " + newSequence); properties.setProperty(ICAToken.NEXT_SEQUENCE_PROPERTY, newSequence); } else { properties.setProperty(certsignkeystr, newKeyLabel); properties.setProperty(KeyStrings.CAKEYPURPOSE_CERTSIGN_STRING_PREVIOUS, keyLabel); // If the key strings are not equal, i.e. crtSignKey and crlSignKey was used instead of just defaultKey // and the keys are the same. Then we need to set both keys to use the new key label if (!StringUtils.equals(certsignkeystr, crlsignkeystr) && StringUtils.equals(keyLabel, crlKeyLabel)) { log.debug("Also setting crlsignkeystr to " + newKeyLabel); properties.setProperty(crlsignkeystr, newKeyLabel); } // Also set the previous sequence properties.setProperty(ICAToken.PREVIOUS_SEQUENCE_PROPERTY, oldSequence); } setProperties(properties); tokentype = "PKCS#11"; // for logging } } else { String msg = intres.getLocalizedMessage("catoken.genkeysnotavail"); log.error(msg); return; } // Store the new sequence permanently. We should not do this earlier, because if an error is thrown generating keys we should not have updated the CA token object if (activate) { log.debug("Setting new sequence: " + newSequence); setKeySequence(newSequence); } // Finally reset the token so it will be re-read when we want to use it this.catoken = null; String msg = intres.getLocalizedMessage("catoken.generatedkeys", tokentype); log.info(msg); if (log.isTraceEnabled()) { log.trace("<generateKeys"); } }
From source file:org.ejbca.util.keystore.KeyStoreContainerBase.java
private X509Certificate getSelfCertificate(String myname, long validity, String sigAlg, KeyPair keyPair) throws Exception { final long currentTime = new Date().getTime(); final Date firstDate = new Date(currentTime - 24 * 60 * 60 * 1000); final Date lastDate = new Date(currentTime + validity * 1000); // Add all mandatory attributes log.debug("keystore signing algorithm " + sigAlg); final PublicKey publicKey = keyPair.getPublic(); if (publicKey == null) { throw new Exception("Public key is null"); }/*from w w w. j a v a 2s . co m*/ final SubjectPublicKeyInfo pkinfo = new SubjectPublicKeyInfo( (ASN1Sequence) ASN1Primitive.fromByteArray(publicKey.getEncoded())); X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder(new X500Name(myname), BigInteger.valueOf(firstDate.getTime()), firstDate, lastDate, new X500Name(myname), pkinfo); final ContentSigner signer = new BufferingContentSigner( new JcaContentSignerBuilder(sigAlg).setProvider(this.providerName).build(keyPair.getPrivate()), 20480); final X509CertificateHolder certHolder = certbuilder.build(signer); return (X509Certificate) CertTools.getCertfromByteArray(certHolder.getEncoded()); }
From source file:net.firejack.platform.installation.processor.InstallSlaveProcessor.java
@Override public void onApplicationEvent(InstallSlaveEvent event) { File keystore = InstallUtils.getKeyStore(); String url = OpenFlameConfig.MASTER_URL.getValue(); String admin = OpenFlameConfig.APP_ADMIN_NAME.getValue(); String password = OpenFlameConfig.APP_ADMIN_PASSWORD.getValue(); try {/*from ww w . j a va 2 s. c o m*/ if (keystore.exists()) { X500Name info = KeyUtils.getInfo(keystore); url = info.getDomain(); } String hostName = InetAddress.getLocalHost().getHostName(); KeyPair keyPair = KeyUtils.generate(keystore); if (keyPair == null) { throw new IllegalStateException("Key not found"); } X509Certificate certificate = KeyUtils.generateCertificate(url, 1, keyPair); if (StringUtils.isBlank(password)) { String cert = new String(Base64.encode(certificate.getEncoded())); OPFEngine.init(url, OpenFlame.PACKAGE, hostName, cert); } else { OPFEngine.init(url, admin, password); } ServerNodeConfig config = new ServerNodeConfig(); config.setServerName(hostName); // config.setServerName(hostName + "_slave"); //TODO [CLUSTER] don't commit this line config.setHost(InetAddress.getLocalHost().getHostAddress()); config.setPort(Integer.decode(OpenFlameConfig.PORT.getValue())); config.setNodeType(ServerNodeType.OPF_SLAVE); config.setLookup(OpenFlame.PACKAGE); config.setCert(certificate.getEncoded()); InputStream stream = OPFEngine.RegistryService.registerSlaveNode(config); ByteArrayOutputStream output = new ByteArrayOutputStream(); IOUtils.copy(stream, output); byte[] decrypted = KeyUtils.decrypt(keyPair.getPrivate(), output.toByteArray()); Map<String, String> map = EnvironmentsUtils.convertFromXml(new ByteArrayInputStream(decrypted)); ConfigContainer.putAll(map); source.refreshDBProperties(); OPFEngine.release(); KeyUtils.add(keystore, keyPair, url); FileUtils.deleteQuietly(InstallUtils.getPropEnv()); } catch (Exception e) { logger.error(e); throw new IllegalStateException(e); } OPFEngine.initialize(); }
From source file:eu.contrail.security.DelegatedUserCertClientTest.java
public void testGetCertInvalidTruststore() throws Exception { System.out.println("%ngetCertInvalidTruststore"); /*//from w w w .j a v a2s. c o m * If the propsFile property isn't set, read the properties files from a hard-wired locationn * */ String propsFile = System.getProperty("propsFile", "./src/test/resources/ucstest.properties"); Properties props = null; try { props = new Properties(); props.load(new FileInputStream(propsFile)); } catch (Exception ex) { System.err.println(ex); } /* * If the targetUrl property isn't set, use a hard-wired URL * */ String uriSpec = "https://one-test.contrail.rl.ac.uk:8443/ca/delegateduser"; KeyPair keyPair = sc.generateKeyPair("RSA", 2048); String signatureAlgorithm = "SHA256withRSA"; String proxyHost = null; String proxyPortSpec = null; String proxyScheme = null; DelegatedHostCertClient instance = new DelegatedHostCertClient(uriSpec, true, "./src/test/resources/keystore.p12", "client", "./src/test/resources/ca-signing-cert.jks", "caserver"); X509Certificate result = null; String userID = "1"; try { System.out.printf("Invalid - Calling %s.%n", uriSpec); result = instance.getCert(keyPair, signatureAlgorithm, userID, true); fail("Should not complete SSL handshakre"); if (result == null) { throw new Exception(); // Throw an Exception to signal test has failed } System.err.println("(Delegeated) User Private Key:"); sc.writeKey(System.out, keyPair.getPrivate()); System.out.println("(Delegeated) User Certificate from CA Server:"); sc.writeCertificate(System.out, result); } catch (javax.net.ssl.SSLPeerUnverifiedException ex) { System.err.append("Caught SSLPeerUnverifiedException as expected"); System.err.printf(ex.getLocalizedMessage()); } catch (Exception ex) { System.err.printf(ex.getLocalizedMessage()); System.err.println("%n"); } }
From source file:org.ejbca.core.protocol.cmp.NestedMessageContentTest.java
@Test public void test02Verify() throws ObjectNotFoundException, InvalidKeyException, SignatureException, AuthorizationDeniedException, EjbcaException, UserDoesntFullfillEndEntityProfile, WaitingForApprovalException, Exception { //------------------- Creating Certificate Request --------------- //PKIMessage crmfMsg = createEESignedCrmfReq(this.subjectDN); byte[] senderNonce = CmpMessageHelper.createSenderNonce(); byte[] transactionID = CmpMessageHelper.createSenderNonce(); Date nb = new Date((new Date()).getTime() - 31536000000L); // not before a year ago Date na = new Date((new Date()).getTime() + 31536000000L); // not afer a yeat from now assertNotNull(nb);/*from w w w. j ava2 s. co m*/ assertNotNull(na); KeyPair keys = null; keys = KeyTools.genKeys("1024", "RSA"); PKIMessage crmfMsg = genCertReq(this.issuerDN, SUBJECT_DN, keys, this.cacert, senderNonce, transactionID, false, null, nb, na, null, null, null); assertNotNull("Failed to create crmfMsg.", crmfMsg); // ---------------- Creating the NestedMessageContent ---------------------- String reqSubjectDN = "CN=bogusSubjectNested"; final byte[] nonce = CmpMessageHelper.createSenderNonce(); final byte[] transid = CmpMessageHelper.createSenderNonce(); PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(new X500Name(reqSubjectDN)), new GeneralName(new X500Name(((X509Certificate) this.cacert).getSubjectDN().getName()))); myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date())); // senderNonce myPKIHeader.setSenderNonce(new DEROctetString(nonce)); // TransactionId myPKIHeader.setTransactionID(new DEROctetString(transid)); //myPKIHeader.addGeneralInfo(new InfoTypeAndValue(ASN1Sequence.getInstance(crmfMsg))); PKIBody myPKIBody = new PKIBody(20, crmfMsg); // NestedMessageContent PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody); KeyPair raKeys = KeyTools.genKeys("1024", "RSA"); createRACertificate("raSignerVerify", "foo123", this.raCertsPath, cmpAlias, raKeys, null, null, CMPTESTPROFILE, this.caid); myPKIMessage = CmpMessageHelper.buildCertBasedPKIProtection(myPKIMessage, null, raKeys.getPrivate(), null, "BC"); assertNotNull("Failed to create myPKIHeader", myPKIHeader); assertNotNull("myPKIBody is null", myPKIBody); assertNotNull("myPKIMessage is null", myPKIMessage); NestedMessageContent nestedMsg = new NestedMessageContent(myPKIMessage, cmpAlias, this.globalConfigurationSession); boolean verify = nestedMsg.verify(); assertTrue("NestedMessageVerification failed.", verify); }
From source file:com.formkiq.core.service.generator.pdfbox.PdfEditorServiceImpl.java
@Override public byte[] sign(final InputStream content) throws IOException { try {/*from ww w . j a v a 2 s. c o m*/ KeyPair key = this.propertyStore.getKeyPair(); PrivateKey privKey = key.getPrivate(); Certificate certificate = this.propertyStore.getCertificate(key); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); org.bouncycastle.asn1.x509.Certificate cert = org.bouncycastle.asn1.x509.Certificate .getInstance(certificate.getEncoded()); ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA256WithRSA").build(privKey); gen.addSignerInfoGenerator( new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build()) .build(sha1Signer, new X509CertificateHolder(cert))); CMSProcessableByteArray msg = new CMSProcessableByteArray(IOUtils.toByteArray(content)); CMSSignedData signedData = gen.generate(msg, false); return signedData.getEncoded(); } catch (GeneralSecurityException | CMSException | OperatorCreationException e) { throw new IOException(e); } }
From source file:org.ejbca.core.protocol.cmp.NestedMessageContentTest.java
@Test public void test04CrmfRACertExist() throws ObjectNotFoundException, InvalidKeyException, SignatureException, AuthorizationDeniedException, EjbcaException, UserDoesntFullfillEndEntityProfile, WaitingForApprovalException, Exception { //------------------- Creating Certificate Request --------------- //PKIMessage crmfMsg = createEESignedCrmfReq(this.subjectDN); byte[] senderNonce = CmpMessageHelper.createSenderNonce(); byte[] transactionID = CmpMessageHelper.createSenderNonce(); Date nb = new Date((new Date()).getTime() - 31536000000L); // not before a year ago Date na = new Date((new Date()).getTime() + 31536000000L); // not afer a yeat from now assertNotNull(nb);//from w w w. java 2 s . c o m assertNotNull(na); KeyPair keys = null; keys = KeyTools.genKeys("1024", "RSA"); PKIMessage crmfReqMsg = genCertReq(this.issuerDN, SUBJECT_DN, keys, this.cacert, senderNonce, transactionID, false, null, nb, na, null, null, null); assertNotNull("Failed to create crmfMsg.", crmfReqMsg); PKIMessage crmfMsg = protectPKIMessage(crmfReqMsg, false, "foo123", 567); CertReqMessages ir = (CertReqMessages) crmfMsg.getBody().getContent(); int reqID = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue(); // ---------------- Creating the NestedMessageContent ---------------------- X500Name reqSubjectDN = new X500Name("CN=bogusSubjectNested"); final byte[] nonce = CmpMessageHelper.createSenderNonce(); final byte[] transid = CmpMessageHelper.createSenderNonce(); PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(reqSubjectDN), new GeneralName(new X500Name(((X509Certificate) this.cacert).getSubjectDN().getName()))); myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date())); // senderNonce myPKIHeader.setSenderNonce(new DEROctetString(nonce)); // TransactionId myPKIHeader.setTransactionID(new DEROctetString(transid)); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(crmfMsg); DERSequence seq = new DERSequence(v); PKIBody myPKIBody = new PKIBody(20, seq); // NestedMessageContent PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody); KeyPair raKeys = KeyTools.genKeys("1024", "RSA"); createRACertificate("raSignerTest04", "foo123", this.raCertsPath, cmpAlias, raKeys, null, null, CMPTESTPROFILE, this.caid); myPKIMessage = CmpMessageHelper.buildCertBasedPKIProtection(myPKIMessage, null, raKeys.getPrivate(), null, "BC"); assertNotNull("Failed to create myPKIHeader", myPKIHeader); assertNotNull("myPKIBody is null", myPKIBody); assertNotNull("myPKIMessage is null", myPKIMessage); final ByteArrayOutputStream bao = new ByteArrayOutputStream(); final DEROutputStream out = new DEROutputStream(bao); out.writeObject(myPKIMessage); final byte[] ba = bao.toByteArray(); // Send request and receive response final byte[] resp = sendCmpHttp(ba, 200, cmpAlias); //final byte[] resp = sendCmpHttp(myPKIMessage.toASN1Primitive().toASN1Object().getEncoded(), 200); // do not check signing if we expect a failure (sFailMessage==null) checkCmpResponseGeneral(resp, this.issuerDN, reqSubjectDN, this.cacert, crmfMsg.getHeader().getSenderNonce().getOctets(), crmfMsg.getHeader().getTransactionID().getOctets(), false, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()); final Certificate cert = checkCmpCertRepMessage(SUBJECT_DN, this.cacert, resp, reqID); assertNotNull("CrmfRequest did not return a certificate", cert); assertTrue(cert instanceof X509Certificate); log.debug("Subject DN of created certificate: " + X500Name.getInstance(((X509Certificate) cert).getSubjectX500Principal().getEncoded())); NestedMessageContent nestedContent = new NestedMessageContent(myPKIMessage, cmpAlias, this.globalConfigurationSession); boolean ret = nestedContent.verify(); assertTrue("The message verification failed, yet the a certificate was returned.", ret); }
From source file:org.ejbca.core.model.ca.catoken.CATokenContainerImpl.java
/** * Method that import CA token keys from a P12 file. Was originally used when upgrading from * old EJBCA versions. Only supports SHA1 and SHA256 with RSA or ECDSA and SHA1 with DSA. *//*from w ww .jav a2 s . c o m*/ public void importKeys(String authenticationCode, PrivateKey privatekey, PublicKey publickey, PrivateKey privateEncryptionKey, PublicKey publicEncryptionKey, Certificate[] caSignatureCertChain) throws Exception { // If we don't give an authentication code, perhaps we have autoactivation enabled char[] authCode = getAuthCodeOrAutoactivationPin(authenticationCode); // Currently only RSA keys are supported KeyStore keystore = KeyStore.getInstance("PKCS12", "BC"); keystore.load(null, null); // The CAs certificate is first in chain Certificate cacert = caSignatureCertChain[0]; // Assume that the same hash algorithm is used for signing that was used to sign this CA cert String signatureAlgorithm = CertTools.getSignatureAlgorithm(cacert); String keyAlg = AlgorithmTools.getKeyAlgorithm(publickey); if (keyAlg == null) { throw new Exception( "Unknown public key type: " + publickey.getAlgorithm() + " (" + publickey.getClass() + ")"); } // If this is a CVC CA we need to find out the sequence if (cacert instanceof CardVerifiableCertificate) { CardVerifiableCertificate cvccacert = (CardVerifiableCertificate) cacert; log.debug("Getting sequence from holderRef in CV certificate."); String sequence = cvccacert.getCVCertificate().getCertificateBody().getHolderReference().getSequence(); log.debug("Setting sequence " + sequence); setKeySequence(sequence); log.debug("Setting default sequence format " + StringTools.KEY_SEQUENCE_FORMAT_NUMERIC); setKeySequenceFormat(StringTools.KEY_SEQUENCE_FORMAT_NUMERIC); } else { log.debug("Setting default sequence " + CATokenConstants.DEFAULT_KEYSEQUENCE); setKeySequence(CATokenConstants.DEFAULT_KEYSEQUENCE); log.debug("Setting default sequence format " + StringTools.KEY_SEQUENCE_FORMAT_NUMERIC); setKeySequenceFormat(StringTools.KEY_SEQUENCE_FORMAT_NUMERIC); } // import sign keys. String keyspec = AlgorithmTools.getKeySpecification(publickey); Certificate[] certchain = new Certificate[1]; certchain[0] = CertTools.genSelfCert("CN=dummy", 36500, null, privatekey, publickey, signatureAlgorithm, true); keystore.setKeyEntry(SoftCAToken.PRIVATESIGNKEYALIAS, privatekey, null, certchain); // generate enc keys. // Encryption keys must be RSA still String encryptionSignatureAlgorithm = AlgorithmTools.getEncSigAlgFromSigAlg(signatureAlgorithm); keyAlg = AlgorithmTools.getKeyAlgorithmFromSigAlg(encryptionSignatureAlgorithm); keyspec = "2048"; KeyPair enckeys = null; if (publicEncryptionKey == null || privateEncryptionKey == null) { enckeys = KeyTools.genKeys(keyspec, keyAlg); } else { enckeys = new KeyPair(publicEncryptionKey, privateEncryptionKey); } // generate dummy certificate certchain[0] = CertTools.genSelfCert("CN=dummy2", 36500, null, enckeys.getPrivate(), enckeys.getPublic(), encryptionSignatureAlgorithm, true); keystore.setKeyEntry(SoftCAToken.PRIVATEDECKEYALIAS, enckeys.getPrivate(), null, certchain); // Store keystore SoftCATokenInfo info = new SoftCATokenInfo(); info.setEncKeyAlgorithm(keyAlg); info.setEncKeySpec(keyspec); info.setEncryptionAlgorithm(encryptionSignatureAlgorithm); info.setSignKeyAlgorithm(keyAlg); info.setSignKeySpec(keyspec); info.setSignatureAlgorithm(signatureAlgorithm); storeSoftKeyStore(authCode, info, null, keystore); // Finally reset the token so it will be re-read when we want to use it this.catoken = null; }
From source file:org.cesecore.keys.util.KeyStoreTools.java
private X509Certificate getSelfCertificate(String myname, long validity, String sigAlg, KeyPair keyPair) throws InvalidKeyException, CertificateException { final long currentTime = new Date().getTime(); final Date firstDate = new Date(currentTime - 24 * 60 * 60 * 1000); final Date lastDate = new Date(currentTime + validity * 1000); final X500Name issuer = new X500Name(myname); final BigInteger serno = BigInteger.valueOf(firstDate.getTime()); final PublicKey publicKey = keyPair.getPublic(); if (publicKey == null) { throw new InvalidKeyException("Public key is null"); }// www . j ava 2 s . c om try { final X509v3CertificateBuilder cg = new JcaX509v3CertificateBuilder(issuer, serno, firstDate, lastDate, issuer, publicKey); log.debug("Keystore signing algorithm " + sigAlg); final ContentSigner signer = new BufferingContentSigner( new JcaContentSignerBuilder(sigAlg).setProvider(this.providerName).build(keyPair.getPrivate()), 20480); final X509CertificateHolder cert = cg.build(signer); return (X509Certificate) CertTools.getCertfromByteArray(cert.getEncoded()); } catch (OperatorCreationException e) { log.error("Error creating content signer: ", e); throw new CertificateException(e); } catch (IOException e) { throw new CertificateException("Could not read certificate", e); } }
From source file:eu.contrail.security.DelegatedUserCertClientTest.java
public void testGetHostCert() throws Exception { System.out.println("getCert"); /*//from w ww . j a v a 2 s. c om * If the propsFile property isn't set, read the properties files from a hard-wired locationn * */ String propsFile = System.getProperty("propsFile", "./src/test/resources/ucstest.properties"); Properties props = null; try { props = new Properties(); props.load(new FileInputStream(propsFile)); } catch (Exception ex) { System.err.println(ex); } /* * If the targetUrl property isn't set, use a hard-wired URL * */ String uriSpec = "https://one-test.contrail.rl.ac.uk:8443/ca/host"; KeyPair keyPair = sc.generateKeyPair("RSA", 2048); String signatureAlgorithm = "SHA256withRSA"; /* * Use a well-known username/password combination * */ String proxyHost = null; String proxyPortSpec = null; String proxyScheme = null; DelegatedHostCertClient instance = new DelegatedHostCertClient(uriSpec, true, "./src/test/resources/keystore.p12", "client", "./src/test/resources/caserver.jks", "caserver"); X509Certificate result = null; String userID = "contrail-client.contrail.rl.ac.uk"; try { System.out.printf("Calling %s.%n", uriSpec); result = instance.getCert(keyPair, signatureAlgorithm, userID, true); if (result == null) { throw new Exception(); // Throw an Exception to signal test has failed } System.out.println("Delegated User Private Key:"); sc.writeKey(System.out, keyPair.getPrivate()); System.out.println("\nDelegated User Certificate from CA Server:"); sc.writeCertificate(System.out, result); } catch (IllegalArgumentException ex) { System.err.printf(ex.getLocalizedMessage()); } }