List of usage examples for java.security KeyPair getPublic
public PublicKey getPublic()
From source file:org.ejbca.core.protocol.ws.EjbcaWSTest.java
/** * Creates a "hardtoken" with certficates. *///from w ww.ja v a 2 s. co m private void createHardToken(String username, String caName, String serialNumber) throws Exception { GlobalConfiguration gc = (GlobalConfiguration) globalConfigurationSession .getCachedConfiguration(GlobalConfiguration.GLOBAL_CONFIGURATION_ID); boolean originalProfileSetting = gc.getEnableEndEntityProfileLimitations(); gc.setEnableEndEntityProfileLimitations(false); globalConfigurationSession.saveConfiguration(intAdmin, gc); if (certificateProfileSession.getCertificateProfileId(WS_TEST_CERTIFICATE_PROFILE_NAME) != 0) { certificateProfileSession.removeCertificateProfile(intAdmin, WS_TEST_CERTIFICATE_PROFILE_NAME); } CertificateProfile profile = new CertificateProfile(CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER); profile.setAllowValidityOverride(true); certificateProfileSession.addCertificateProfile(intAdmin, WS_TEST_CERTIFICATE_PROFILE_NAME, profile); UserDataVOWS tokenUser1 = new UserDataVOWS(); tokenUser1.setUsername(username); tokenUser1.setPassword(PASSWORD); tokenUser1.setClearPwd(true); tokenUser1.setSubjectDN("CN=" + username); tokenUser1.setCaName(caName); tokenUser1.setEmail(null); tokenUser1.setSubjectAltName(null); tokenUser1.setStatus(UserDataVOWS.STATUS_NEW); tokenUser1.setTokenType(UserDataVOWS.TOKEN_TYPE_USERGENERATED); tokenUser1.setEndEntityProfileName("EMPTY"); tokenUser1.setCertificateProfileName("ENDUSER"); KeyPair basickeys = KeyTools.genKeys("1024", AlgorithmConstants.KEYALGORITHM_RSA); PKCS10CertificationRequest basicpkcs10 = CertTools.genPKCS10CertificationRequest("SHA256WithRSA", CertTools.stringToBcX500Name("CN=NOTUSED"), basickeys.getPublic(), new DERSet(), basickeys.getPrivate(), null); ArrayList<TokenCertificateRequestWS> requests = new ArrayList<TokenCertificateRequestWS>(); TokenCertificateRequestWS tokenCertReqWS = new TokenCertificateRequestWS(); tokenCertReqWS.setCAName(caName); tokenCertReqWS.setCertificateProfileName(WS_TEST_CERTIFICATE_PROFILE_NAME); tokenCertReqWS.setValidityIdDays("1"); tokenCertReqWS.setPkcs10Data(basicpkcs10.getEncoded()); tokenCertReqWS.setType(HardTokenConstants.REQUESTTYPE_PKCS10_REQUEST); requests.add(tokenCertReqWS); tokenCertReqWS = new TokenCertificateRequestWS(); tokenCertReqWS.setCAName(caName); tokenCertReqWS.setCertificateProfileName("ENDUSER"); tokenCertReqWS.setKeyalg("RSA"); tokenCertReqWS.setKeyspec("1024"); tokenCertReqWS.setType(HardTokenConstants.REQUESTTYPE_KEYSTORE_REQUEST); requests.add(tokenCertReqWS); HardTokenDataWS hardTokenDataWS = new HardTokenDataWS(); hardTokenDataWS.setLabel(HardTokenConstants.LABEL_PROJECTCARD); hardTokenDataWS.setTokenType(HardTokenConstants.TOKENTYPE_SWEDISHEID); hardTokenDataWS.setHardTokenSN(serialNumber); PinDataWS basicPinDataWS = new PinDataWS(); basicPinDataWS.setType(HardTokenConstants.PINTYPE_BASIC); basicPinDataWS.setInitialPIN("1234"); basicPinDataWS.setPUK("12345678"); PinDataWS signaturePinDataWS = new PinDataWS(); signaturePinDataWS.setType(HardTokenConstants.PINTYPE_SIGNATURE); signaturePinDataWS.setInitialPIN("5678"); signaturePinDataWS.setPUK("23456789"); hardTokenDataWS.getPinDatas().add(basicPinDataWS); hardTokenDataWS.getPinDatas().add(signaturePinDataWS); List<TokenCertificateResponseWS> responses = ejbcaraws.genTokenCertificates(tokenUser1, requests, hardTokenDataWS, true, false); assertTrue(responses.size() == 2); certificateProfileSession.removeCertificateProfile(intAdmin, WS_TEST_CERTIFICATE_PROFILE_NAME); gc.setEnableEndEntityProfileLimitations(originalProfileSetting); globalConfigurationSession.saveConfiguration(intAdmin, gc); }
From source file:org.ejbca.core.protocol.ws.EjbcaWSTest.java
private void testCertificateRequestWithEeiDnOverride(boolean allowDNOverrideByEndEntityInformation, boolean useCsr, String requestedSubjectDN, String expectedSubjectDN) throws Exception { if (certificateProfileSession.getCertificateProfileId(WS_TEST_CERTIFICATE_PROFILE_NAME) != 0) { certificateProfileSession.removeCertificateProfile(intAdmin, WS_TEST_CERTIFICATE_PROFILE_NAME); }/*from www.ja va2s .co m*/ CertificateProfile profile = new CertificateProfile(CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER); profile.setAllowDNOverrideByEndEntityInformation(allowDNOverrideByEndEntityInformation); certificateProfileSession.addCertificateProfile(intAdmin, WS_TEST_CERTIFICATE_PROFILE_NAME, profile); //This test will fail if EEP limitations are enabled GlobalConfiguration originalConfiguration = (GlobalConfiguration) globalConfigurationSession .getCachedConfiguration(GlobalConfiguration.GLOBAL_CONFIGURATION_ID); GlobalConfiguration globalConfiguration = (GlobalConfiguration) globalConfigurationSession .getCachedConfiguration(GlobalConfiguration.GLOBAL_CONFIGURATION_ID); globalConfiguration.setEnableEndEntityProfileLimitations(false); globalConfigurationSession.saveConfiguration(intAdmin, globalConfiguration); try { String userName = "eeiDnOverride" + secureRandom.nextLong(); final UserDataVOWS userData = new UserDataVOWS(); userData.setUsername(userName); userData.setPassword(PASSWORD); userData.setClearPwd(true); userData.setSubjectDN(requestedSubjectDN); userData.setCaName(getAdminCAName()); userData.setEmail(null); userData.setSubjectAltName(null); userData.setStatus(UserDataVOWS.STATUS_NEW); userData.setTokenType(UserDataVOWS.TOKEN_TYPE_P12); userData.setEndEntityProfileName("EMPTY"); userData.setCertificateProfileName(WS_TEST_CERTIFICATE_PROFILE_NAME); final X509Certificate cert; if (useCsr) { KeyPair keys = KeyTools.genKeys("1024", AlgorithmConstants.KEYALGORITHM_RSA); PKCS10CertificationRequest pkcs10 = CertTools.genPKCS10CertificationRequest("SHA256WithRSA", CertTools.stringToBcX500Name("CN=NOUSED"), keys.getPublic(), new DERSet(), keys.getPrivate(), null); final String csr = new String(Base64.encode(pkcs10.toASN1Structure().getEncoded())); CertificateResponse response = ejbcaraws.certificateRequest(userData, csr, CertificateHelper.CERT_REQ_TYPE_PKCS10, null, CertificateHelper.RESPONSETYPE_CERTIFICATE); cert = response.getCertificate(); } else { KeyStore ksenv = ejbcaraws.softTokenRequest(userData, null, "1024", AlgorithmConstants.KEYALGORITHM_RSA); java.security.KeyStore keyStore = KeyStoreHelper.getKeyStore(ksenv.getKeystoreData(), "PKCS12", PASSWORD); assertNotNull(keyStore); Enumeration<String> en = keyStore.aliases(); String alias = en.nextElement(); if (!keyStore.isKeyEntry(alias)) { alias = en.nextElement(); } cert = (X509Certificate) keyStore.getCertificate(alias); } final List<Certificate> certificates = Arrays.asList(new Certificate[] { cert }); log.info(certificates.size() + " certs.\n" + new String(CertTools.getPemFromCertificateChain(certificates))); X500Name x500name = new JcaX509CertificateHolder(cert).getSubject(); String resultingSubjectDN = CeSecoreNameStyle.INSTANCE.toString(x500name); log.debug("x500name: " + resultingSubjectDN); assertEquals("Unexpected transformation.", expectedSubjectDN, resultingSubjectDN); try { endEntityManagementSession.deleteUser(intAdmin, userName); } catch (NotFoundException e) { // Ignore } } finally { if (certificateProfileSession.getCertificateProfileId(WS_TEST_CERTIFICATE_PROFILE_NAME) != 0) { certificateProfileSession.removeCertificateProfile(intAdmin, WS_TEST_CERTIFICATE_PROFILE_NAME); } globalConfigurationSession.saveConfiguration(intAdmin, originalConfiguration); } }
From source file:com.mirth.connect.server.controllers.DefaultConfigurationController.java
/** * Checks for an existing certificate to use for secure communication between the server and * client. If no certficate exists, this will generate a new one. * //from w w w . j av a 2 s . co m */ private void generateDefaultCertificate(Provider provider, KeyStore keyStore, char[] keyPassword) throws Exception { final String certificateAlias = "mirthconnect"; if (!keyStore.containsAlias(certificateAlias)) { // Common CA and SSL cert attributes Date startDate = new Date(); // time from which certificate is valid Date expiryDate = DateUtils.addYears(startDate, 50); // time after which certificate is not valid KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", provider); keyPairGenerator.initialize(2048); KeyPair caKeyPair = keyPairGenerator.generateKeyPair(); logger.debug("generated new key pair for CA cert using provider: " + provider.getName()); // Generate CA cert X500Name caSubjectName = new X500Name("CN=Mirth Connect Certificate Authority"); SubjectPublicKeyInfo caSubjectKey = new SubjectPublicKeyInfo( ASN1Sequence.getInstance(caKeyPair.getPublic().getEncoded())); X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(caSubjectName, BigInteger.ONE, startDate, expiryDate, caSubjectName, caSubjectKey); certBuilder.addExtension(org.bouncycastle.asn1.x509.Extension.basicConstraints, true, new BasicConstraints(0)); ContentSigner sigGen = new JcaContentSignerBuilder("SHA256withRSA").setProvider(provider) .build(caKeyPair.getPrivate()); Certificate caCert = new JcaX509CertificateConverter().setProvider(provider) .getCertificate(certBuilder.build(sigGen)); // Generate SSL cert KeyPair sslKeyPair = keyPairGenerator.generateKeyPair(); logger.debug("generated new key pair for SSL cert using provider: " + provider.getName()); X500Name sslSubjectName = new X500Name("CN=mirth-connect"); SubjectPublicKeyInfo sslSubjectKey = new SubjectPublicKeyInfo( ASN1Sequence.getInstance(sslKeyPair.getPublic().getEncoded())); X509v3CertificateBuilder sslCertBuilder = new X509v3CertificateBuilder(caSubjectName, new BigInteger(50, new SecureRandom()), startDate, expiryDate, sslSubjectName, sslSubjectKey); sslCertBuilder.addExtension(org.bouncycastle.asn1.x509.Extension.authorityKeyIdentifier, false, new AuthorityKeyIdentifier(caCert.getEncoded())); sslCertBuilder.addExtension(org.bouncycastle.asn1.x509.Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifier(sslKeyPair.getPublic().getEncoded())); sigGen = new JcaContentSignerBuilder("SHA256withRSA").setProvider(provider) .build(caKeyPair.getPrivate()); Certificate sslCert = new JcaX509CertificateConverter().setProvider(provider) .getCertificate(sslCertBuilder.build(sigGen)); logger.debug("generated new certificate with serial number: " + ((X509Certificate) sslCert).getSerialNumber()); // add the generated SSL cert to the keystore using the key password keyStore.setKeyEntry(certificateAlias, sslKeyPair.getPrivate(), keyPassword, new Certificate[] { sslCert }); } else { logger.debug("found certificate in keystore"); } }
From source file:com.netscape.cmsutil.crypto.CryptoUtil.java
public static PKCS10 createCertificationRequest(String subjectName, KeyPair keyPair, String alg) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, IOException, CertificateException, SignatureException { PublicKey pubk = keyPair.getPublic(); X509Key key = convertPublicKeyToX509Key(pubk); java.security.Signature sig = java.security.Signature.getInstance(alg, "Mozilla-JSS"); sig.initSign(keyPair.getPrivate());//from w w w . jav a 2s . co m PKCS10 pkcs10 = new PKCS10(key); X500Name name = new X500Name(subjectName); X500Signer signer = new X500Signer(sig, name); pkcs10.encodeAndSign(signer); return pkcs10; }
From source file:com.netscape.cmsutil.crypto.CryptoUtil.java
/** * Creates a Certificate template./*w w w.j a v a 2s. com*/ */ public static X509CertInfo createX509CertInfo(KeyPair pair, int serialno, String issuername, String subjname, Date notBefore, Date notAfter) throws IOException, CertificateException, InvalidKeyException { return createX509CertInfo(convertPublicKeyToX509Key(pair.getPublic()), serialno, issuername, subjname, notBefore, notAfter); }
From source file:com.netscape.cmsutil.crypto.CryptoUtil.java
/** * Creates a PKCS#10 request.//from w w w . j av a 2 s. c o m */ public static PKCS10 createCertificationRequest(String subjectName, KeyPair keyPair) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, IOException, CertificateException, SignatureException { String alg; PublicKey pubk = keyPair.getPublic(); X509Key key = convertPublicKeyToX509Key(pubk); if (pubk instanceof RSAPublicKey) { alg = "SHA256withRSA"; } else if (isECCKey(key)) { alg = "SHA256withEC"; } else { // Assert.assert(pubk instanceof DSAPublicKey); alg = "DSA"; } return createCertificationRequest(subjectName, keyPair, alg); }
From source file:org.cesecore.certificates.ca.X509CA.java
/** * @see CA#createRequest(Collection, String, Certificate, int) */// www .ja v a 2s . co m @Override public byte[] createRequest(CryptoToken cryptoToken, Collection<ASN1Encodable> attributes, String signAlg, Certificate cacert, int signatureKeyPurpose) throws CryptoTokenOfflineException { log.trace( ">createRequest: " + signAlg + ", " + CertTools.getSubjectDN(cacert) + ", " + signatureKeyPurpose); ASN1Set attrset = new DERSet(); if (attributes != null) { log.debug("Adding attributes in the request"); Iterator<ASN1Encodable> iter = attributes.iterator(); ASN1EncodableVector vec = new ASN1EncodableVector(); while (iter.hasNext()) { ASN1Encodable o = (ASN1Encodable) iter.next(); vec.add(o); } attrset = new DERSet(vec); } final X500NameStyle nameStyle; if (getUsePrintableStringSubjectDN()) { nameStyle = PrintableStringNameStyle.INSTANCE; } else { nameStyle = CeSecoreNameStyle.INSTANCE; } X500Name x509dn = CertTools.stringToBcX500Name(getSubjectDN(), nameStyle, getUseLdapDNOrder()); PKCS10CertificationRequest req; try { final CAToken catoken = getCAToken(); final String alias = catoken.getAliasFromPurpose(signatureKeyPurpose); final KeyPair keyPair = new KeyPair(cryptoToken.getPublicKey(alias), cryptoToken.getPrivateKey(alias)); req = CertTools.genPKCS10CertificationRequest(signAlg, x509dn, keyPair.getPublic(), attrset, keyPair.getPrivate(), cryptoToken.getSignProviderName()); log.trace("<createRequest"); return req.getEncoded(); } catch (CryptoTokenOfflineException e) { // NOPMD, since we catch wide below throw e; } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.texai.x509.X509Utils.java
/** Generates a self-signed certificate to use as a CA root certificate. * * @param keyPair the root public/private key pair * @return a self-signed CA root certificate * * @throws CertificateEncodingException when the certificate cannot be encoded * @throws NoSuchProviderException when an invalid provider is given * @throws NoSuchAlgorithmException when an invalid algorithm is given * @throws SignatureException when the an invalid signature is present * @throws InvalidKeyException when the given key is invalid * @throws IOException if an input/output error occurs while processing the serial number file *//*from ww w.j ava2 s. co m*/ protected static X509Certificate generateRootX509Certificate(final KeyPair keyPair) throws CertificateEncodingException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, InvalidKeyException, IOException { //Preconditions assert keyPair != null : "keyPair must not be null"; final UUID rootUUID = UUID.randomUUID(); // provide items to X500Principal in reverse order final X500Principal rootX500Principal = new X500Principal( "UID=" + rootUUID + ", O=Texai Certification Authority, CN=texai.org"); final X500Name subject = new X500Name(rootX500Principal.getName()); final X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder( new X500Name(rootX500Principal.getName()), // issuer, getNextSerialNumber(), // serial new Date(System.currentTimeMillis() - 10000L), // notBefore, new Date(System.currentTimeMillis() + VALIDITY_PERIOD), // notAfter, subject, new SubjectPublicKeyInfo(ASN1Sequence.getInstance(keyPair.getPublic().getEncoded()))); // publicKeyInfo // see http://www.ietf.org/rfc/rfc3280.txt // see http://stackoverflow.com/questions/20175447/creating-certificates-for-ssl-communication final JcaX509ExtensionUtils jcaX509ExtensionUtils = new JcaX509ExtensionUtils(); // Add subject key identifier x509v3CertificateBuilder.addExtension(Extension.subjectKeyIdentifier, false, // isCritical jcaX509ExtensionUtils.createSubjectKeyIdentifier(keyPair.getPublic())); // add basic constraints x509v3CertificateBuilder.addExtension(Extension.basicConstraints, true, // isCritical new BasicConstraints(true)); // is a CA certificate with an unlimited certification path length final KeyUsage keyUsage = new KeyUsage( // the keyCertSign bit indicates that the subject public key may be used for verifying a signature on // certificates KeyUsage.keyCertSign | // the cRLSign indicates that the subject public key may be used for verifying a signature on revocation // information KeyUsage.cRLSign); // add key usage x509v3CertificateBuilder.addExtension(Extension.keyUsage, true, // isCritical keyUsage); X509Certificate rootX509Certificate; try { final ContentSigner contentSigner = new JcaContentSignerBuilder(DIGITAL_SIGNATURE_ALGORITHM) .setProvider(BOUNCY_CASTLE_PROVIDER).build(keyPair.getPrivate()); final X509CertificateHolder x509CertificateHolder = x509v3CertificateBuilder.build(contentSigner); final JcaX509CertificateConverter jcaX509CertificateConverter = new JcaX509CertificateConverter(); rootX509Certificate = jcaX509CertificateConverter.getCertificate(x509CertificateHolder); } catch (CertificateException | OperatorCreationException ex) { throw new TexaiException(ex); } //Postconditions try { rootX509Certificate.checkValidity(); rootX509Certificate.verify(keyPair.getPublic()); return rootX509Certificate; } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchProviderException | SignatureException | CertificateException ex) { throw new TexaiException(ex); } }
From source file:com.netscape.cmsutil.crypto.CryptoUtil.java
public static KeyIdentifier createKeyIdentifier(KeyPair keypair) throws NoSuchAlgorithmException, InvalidKeyException { String method = "CryptoUtil: createKeyIdentifier: "; logger.debug(method + "begins"); X509Key subjectKeyInfo = convertPublicKeyToX509Key(keypair.getPublic()); byte[] hash = generateKeyIdentifier(subjectKeyInfo.getKey()); if (hash == null) { logger.debug(method + "generateKeyIdentifier returns null"); return null; }/* w w w.ja va 2s . c o m*/ return new KeyIdentifier(hash); }
From source file:org.ejbca.core.protocol.scep.ProtocolScepHttpTest.java
private byte[] genScepRequest(boolean makeCrlReq, String digestoid, String userDN, KeyPair keyPair, String signatureProvider) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException, SignatureException, InvalidAlgorithmParameterException, CertStoreException, IOException, CMSException, OperatorCreationException, CertificateException { ScepRequestGenerator gen = new ScepRequestGenerator(); gen.setKeys(keyPair, signatureProvider); gen.setDigestOid(digestoid);// ww w.j a v a 2 s. c o m byte[] msgBytes = null; // Create a transactionId byte[] randBytes = new byte[16]; this.rand.nextBytes(randBytes); byte[] digest = CertTools.generateMD5Fingerprint(randBytes); transId = new String(Base64.encode(digest)); final X509Certificate senderCertificate = CertTools.genSelfCert("CN=SenderCertificate", 24 * 60 * 60 * 1000, null, keyPair.getPrivate(), keyPair.getPublic(), AlgorithmConstants.SIGALG_SHA1_WITH_RSA, false); if (makeCrlReq) { msgBytes = gen.generateCrlReq(userDN, transId, cacert, senderCertificate, keyPair.getPrivate()); } else { msgBytes = gen.generateCertReq(userDN, "foo123", transId, cacert, senderCertificate, keyPair.getPrivate()); } assertNotNull(msgBytes); senderNonce = gen.getSenderNonce(); byte[] nonceBytes = Base64.decode(senderNonce.getBytes()); assertTrue(nonceBytes.length == 16); return msgBytes; }