List of usage examples for java.security PublicKey getClass
@HotSpotIntrinsicCandidate public final native Class<?> getClass();
From source file:com.google.api.auth.DefaultJwksSupplier.java
private static JsonWebKey toJsonWebKey(PublicKey publicKey) { if (publicKey instanceof RSAPublicKey) { return new RsaJsonWebKey((RSAPublicKey) publicKey); } else if (publicKey instanceof ECPublicKey) { return new EllipticCurveJsonWebKey((ECPublicKey) publicKey); }//from ww w. ja v a 2 s.c o m String message = "Unsupported public key type: " + publicKey.getClass().getSimpleName(); throw new UnauthenticatedException(message); }
From source file:com.netscape.cms.servlet.csadmin.ConfigurationUtils.java
public static void storeKeyPair(IConfigStore config, String tag, KeyPair pair) throws TokenException, EBaseException { logger.debug("ConfigurationUtils: storeKeyPair(" + tag + ")"); PublicKey publicKey = pair.getPublic(); if (publicKey instanceof RSAPublicKey) { RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey; byte modulus[] = rsaPublicKey.getModulus().toByteArray(); config.putString(PCERT_PREFIX + tag + ".pubkey.modulus", CryptoUtil.byte2string(modulus)); byte exponent[] = rsaPublicKey.getPublicExponent().toByteArray(); config.putString(PCERT_PREFIX + tag + ".pubkey.exponent", CryptoUtil.byte2string(exponent)); } else { // ECC logger.debug("ConfigurationUtils: Public key class: " + publicKey.getClass().getName()); byte encoded[] = publicKey.getEncoded(); config.putString(PCERT_PREFIX + tag + ".pubkey.encoded", CryptoUtil.byte2string(encoded)); }/*from ww w . j ava 2 s .co m*/ PrivateKey privateKey = (PrivateKey) pair.getPrivate(); byte id[] = privateKey.getUniqueID(); String kid = CryptoUtil.encodeKeyID(id); config.putString(PCERT_PREFIX + tag + ".privkey.id", kid); String keyAlgo = config.getString(PCERT_PREFIX + tag + ".signingalgorithm"); setSigningAlgorithm(tag, keyAlgo, config); }
From source file:org.cesecore.certificates.certificate.CertificateCreateSessionBean.java
/** * Checks that a public key sent in a request fulfills the policy in the CertificateProfile * //from w ww.j av a 2s .c o m * @param pk PublicKey sent in request * @param certProfile CertificateProfile with the key policy (length restrictions) * @throws IllegalKeyException if the PublicKey does not fulfill policy in CertificateProfile */ private void verifyKey(final PublicKey pk, final CertificateProfile certProfile) throws IllegalKeyException { // Verify key length that it is compliant with certificate profile final int keyLength = KeyTools.getKeyLength(pk); if (log.isDebugEnabled()) { log.debug("Keylength = " + keyLength); } if (keyLength == -1) { final String text = intres.getLocalizedMessage("createcert.unsupportedkeytype", pk.getClass().getName()); // logSession.log(admin, data.getCAId(), LogConstants.MODULE_CA, new java.util.Date(), data.getUsername(), null, // LogConstants.EVENT_INFO_CREATECERTIFICATE, text); throw new IllegalKeyException(text); } if ((keyLength < (certProfile.getMinimumAvailableBitLength() - 1)) || (keyLength > (certProfile.getMaximumAvailableBitLength()))) { final String text = intres.getLocalizedMessage("createcert.illegalkeylength", Integer.valueOf(keyLength)); // logSession.log(admin, data.getCAId(), LogConstants.MODULE_CA, new java.util.Date(), data.getUsername(), null, // LogConstants.EVENT_INFO_CREATECERTIFICATE, text); throw new IllegalKeyException(text); } }
From source file:org.cesecore.keys.util.KeyTools.java
/** * Testing a key pair to verify that it is possible to first sign and then verify with it. * // w ww . j a v a2 s . com * @param priv * private key to sign a string with * @param pub * public key to verify the signature with * @param provider * A provider used for signing with the private key, or null if "BC" should be used. * * @throws InvalidKeyException * if the public key can not be used to verify a string signed by the private key, because the key is wrong or the signature operation * fails for other reasons such as a NoSuchAlgorithmException or SignatureException. * @throws NoSuchProviderException * if the provider is not installed. */ public static void testKey(final PrivateKey priv, final PublicKey pub, final String provider) throws InvalidKeyException { // NOPMD:this is not a junit test final byte input[] = "Lillan gick pa vagen ut, motte dar en katt...".getBytes(); final byte signBV[]; final String testSigAlg; { final Iterator<String> i = AlgorithmTools.getSignatureAlgorithms(pub).iterator(); final String tmp = i.hasNext() ? i.next() : null; testSigAlg = tmp != null ? tmp : "SHA1WithRSA"; } if (log.isDebugEnabled()) { log.debug("Testing keys with algorithm: " + pub.getAlgorithm()); log.debug("testSigAlg: " + testSigAlg); log.debug("provider: " + provider); log.trace("privateKey: " + priv); log.trace("privateKey class: " + priv.getClass().getName()); log.trace("publicKey: " + pub); log.trace("publicKey class: " + pub.getClass().getName()); } try { { final Provider prov = Security.getProvider(provider != null ? provider : "BC"); final Signature signature = Signature.getInstance(testSigAlg, prov); signature.initSign(priv); signature.update(input); signBV = signature.sign(); if (signBV == null) { throw new InvalidKeyException("Result from signing is null."); } if (log.isDebugEnabled()) { log.trace("Created signature of size: " + signBV.length); log.trace("Created signature: " + new String(Hex.encode(signBV))); } } { Signature signature; try { signature = Signature.getInstance(testSigAlg, "BC"); } catch (NoSuchProviderException e) { throw new IllegalStateException("BouncyCastle was not found as a provider.", e); } signature.initVerify(pub); signature.update(input); if (!signature.verify(signBV)) { throw new InvalidKeyException("Not possible to sign and then verify with key pair."); } } } catch (NoSuchAlgorithmException e) { throw new InvalidKeyException("Exception testing key: " + e.getMessage(), e); } catch (SignatureException e) { throw new InvalidKeyException("Exception testing key: " + e.getMessage(), e); } }
From source file:org.cesecore.util.CertTools.java
public static X509Certificate genSelfCertForPurpose(String dn, long validity, String policyId, PrivateKey privKey, PublicKey pubKey, String sigAlg, boolean isCA, int keyusage, Date privateKeyNotBefore, Date privateKeyNotAfter, String provider, boolean ldapOrder, List<Extension> additionalExtensions) throws CertificateParsingException, IOException, OperatorCreationException { // Create self signed certificate Date firstDate = new Date(); // Set back startdate ten minutes to avoid some problems with wrongly set clocks. firstDate.setTime(firstDate.getTime() - (10 * 60 * 1000)); Date lastDate = new Date(); // validity in days = validity*24*60*60*1000 milliseconds lastDate.setTime(lastDate.getTime() + (validity * (24 * 60 * 60 * 1000))); // Transform the PublicKey to be sure we have it in a format that the X509 certificate generator handles, it might be // a CVC public key that is passed as parameter PublicKey publicKey = null;//w ww . j a v a2s . c o m if (pubKey instanceof RSAPublicKey) { RSAPublicKey rsapk = (RSAPublicKey) pubKey; RSAPublicKeySpec rSAPublicKeySpec = new RSAPublicKeySpec(rsapk.getModulus(), rsapk.getPublicExponent()); try { publicKey = KeyFactory.getInstance("RSA").generatePublic(rSAPublicKeySpec); } catch (InvalidKeySpecException e) { log.error("Error creating RSAPublicKey from spec: ", e); publicKey = pubKey; } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("RSA was not a known algorithm", e); } } else if (pubKey instanceof ECPublicKey) { ECPublicKey ecpk = (ECPublicKey) pubKey; try { ECPublicKeySpec ecspec = new ECPublicKeySpec(ecpk.getW(), ecpk.getParams()); // will throw NPE if key is "implicitlyCA" final String algo = ecpk.getAlgorithm(); if (algo.equals(AlgorithmConstants.KEYALGORITHM_ECGOST3410)) { try { publicKey = KeyFactory.getInstance("ECGOST3410").generatePublic(ecspec); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("ECGOST3410 was not a known algorithm", e); } } else if (algo.equals(AlgorithmConstants.KEYALGORITHM_DSTU4145)) { try { publicKey = KeyFactory.getInstance("DSTU4145").generatePublic(ecspec); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("DSTU4145 was not a known algorithm", e); } } else { try { publicKey = KeyFactory.getInstance("EC").generatePublic(ecspec); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("EC was not a known algorithm", e); } } } catch (InvalidKeySpecException e) { log.error("Error creating ECPublicKey from spec: ", e); publicKey = pubKey; } catch (NullPointerException e) { log.debug("NullPointerException, probably it is implicitlyCA generated keys: " + e.getMessage()); publicKey = pubKey; } } else { log.debug("Not converting key of class. " + pubKey.getClass().getName()); publicKey = pubKey; } // Serialnumber is random bits, where random generator is initialized with Date.getTime() when this // bean is created. byte[] serno = new byte[8]; SecureRandom random; try { random = SecureRandom.getInstance("SHA1PRNG"); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("SHA1PRNG was not a known algorithm", e); } random.setSeed(new Date().getTime()); random.nextBytes(serno); SubjectPublicKeyInfo pkinfo; try { pkinfo = new SubjectPublicKeyInfo((ASN1Sequence) ASN1Primitive.fromByteArray(publicKey.getEncoded())); } catch (IOException e) { throw new IllegalArgumentException("Provided public key could not be read to ASN1Primitive", e); } X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder( CertTools.stringToBcX500Name(dn, ldapOrder), new BigInteger(serno).abs(), firstDate, lastDate, CertTools.stringToBcX500Name(dn, ldapOrder), pkinfo); // Basic constranits is always critical and MUST be present at-least in CA-certificates. BasicConstraints bc = new BasicConstraints(isCA); certbuilder.addExtension(Extension.basicConstraints, true, bc); // Put critical KeyUsage in CA-certificates if (isCA || keyusage != 0) { X509KeyUsage ku = new X509KeyUsage(keyusage); certbuilder.addExtension(Extension.keyUsage, true, ku); } if ((privateKeyNotBefore != null) || (privateKeyNotAfter != null)) { final ASN1EncodableVector v = new ASN1EncodableVector(); if (privateKeyNotBefore != null) { v.add(new DERTaggedObject(false, 0, new DERGeneralizedTime(privateKeyNotBefore))); } if (privateKeyNotAfter != null) { v.add(new DERTaggedObject(false, 1, new DERGeneralizedTime(privateKeyNotAfter))); } certbuilder.addExtension(Extension.privateKeyUsagePeriod, false, new DERSequence(v)); } // Subject and Authority key identifier is always non-critical and MUST be present for certificates to verify in Firefox. try { if (isCA) { ASN1InputStream sAsn1InputStream = new ASN1InputStream( new ByteArrayInputStream(publicKey.getEncoded())); ASN1InputStream aAsn1InputStream = new ASN1InputStream( new ByteArrayInputStream(publicKey.getEncoded())); try { SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo( (ASN1Sequence) sAsn1InputStream.readObject()); X509ExtensionUtils x509ExtensionUtils = new BcX509ExtensionUtils(); SubjectKeyIdentifier ski = x509ExtensionUtils.createSubjectKeyIdentifier(spki); SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo( (ASN1Sequence) aAsn1InputStream.readObject()); AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki); certbuilder.addExtension(Extension.subjectKeyIdentifier, false, ski); certbuilder.addExtension(Extension.authorityKeyIdentifier, false, aki); } finally { sAsn1InputStream.close(); aAsn1InputStream.close(); } } } catch (IOException e) { // do nothing } // CertificatePolicies extension if supplied policy ID, always non-critical if (policyId != null) { PolicyInformation pi = new PolicyInformation(new ASN1ObjectIdentifier(policyId)); DERSequence seq = new DERSequence(pi); certbuilder.addExtension(Extension.certificatePolicies, false, seq); } // Add any additional if (additionalExtensions != null) { for (final Extension extension : additionalExtensions) { certbuilder.addExtension(extension.getExtnId(), extension.isCritical(), extension.getParsedValue()); } } final ContentSigner signer = new BufferingContentSigner( new JcaContentSignerBuilder(sigAlg).setProvider(provider).build(privKey), 20480); final X509CertificateHolder certHolder = certbuilder.build(signer); final X509Certificate selfcert = (X509Certificate) CertTools.getCertfromByteArray(certHolder.getEncoded()); return selfcert; }
From source file:org.ejbca.core.ejb.ca.caadmin.CAAdminSessionBean.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.// ww w . j a va 2 s .c o m * @throws OperatorCreationException * @throws AuthorizationDeniedException */ private CAToken importKeysToCAToken(AuthenticationToken authenticationToken, String authenticationCode, Properties caTokenProperties, PrivateKey privatekey, PublicKey publickey, PrivateKey privateEncryptionKey, PublicKey publicEncryptionKey, Certificate[] caSignatureCertChain, int caId) throws CryptoTokenAuthenticationFailedException, IllegalCryptoTokenException, OperatorCreationException, AuthorizationDeniedException { // If we don't give an authentication code, perhaps we have autoactivation enabled if (StringUtils.isEmpty(authenticationCode)) { String msg = intres.getLocalizedMessage("token.authcodemissing", Integer.valueOf(caId)); log.info(msg); throw new CryptoTokenAuthenticationFailedException(msg); } if (caTokenProperties == null) { caTokenProperties = new Properties(); } try { // 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 = AlgorithmTools.getSignatureAlgorithm(cacert); String keyAlg = AlgorithmTools.getKeyAlgorithm(publickey); if (keyAlg == null) { throw new IllegalCryptoTokenException( "Unknown public key type: " + publickey.getAlgorithm() + " (" + publickey.getClass() + ")"); } // import sign keys. final Certificate[] certchain = new Certificate[1]; certchain[0] = CertTools.genSelfCert("CN=dummy", 36500, null, privatekey, publickey, signatureAlgorithm, true); keystore.setKeyEntry(CAToken.SOFTPRIVATESIGNKEYALIAS, privatekey, null, certchain); // generate enc keys. // Encryption keys must be RSA still final String encryptionAlgorithm = AlgorithmTools.getEncSigAlgFromSigAlg(signatureAlgorithm); keyAlg = AlgorithmTools.getKeyAlgorithmFromSigAlg(encryptionAlgorithm); final String enckeyspec = "2048"; KeyPair enckeys = null; if (publicEncryptionKey == null || privateEncryptionKey == null) { enckeys = KeyTools.genKeys(enckeyspec, keyAlg); } else { enckeys = new KeyPair(publicEncryptionKey, privateEncryptionKey); } // generate dummy certificate certchain[0] = CertTools.genSelfCert("CN=dummy2", 36500, null, enckeys.getPrivate(), enckeys.getPublic(), encryptionAlgorithm, true); keystore.setKeyEntry(CAToken.SOFTPRIVATEDECKEYALIAS, enckeys.getPrivate(), null, certchain); // Set the token properties caTokenProperties.setProperty(CATokenConstants.CAKEYPURPOSE_CERTSIGN_STRING, CAToken.SOFTPRIVATESIGNKEYALIAS); caTokenProperties.setProperty(CATokenConstants.CAKEYPURPOSE_CRLSIGN_STRING, CAToken.SOFTPRIVATESIGNKEYALIAS); caTokenProperties.setProperty(CATokenConstants.CAKEYPURPOSE_DEFAULT_STRING, CAToken.SOFTPRIVATEDECKEYALIAS); // Write the keystore to byte[] that we can feed to crypto token factory final char[] authCode = authenticationCode.toCharArray(); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); keystore.store(baos, authCode); // Now we have the PKCS12 keystore, from this we can create the CAToken final Properties cryptoTokenProperties = new Properties(); int cryptoTokenId; try { cryptoTokenId = createCryptoTokenWithUniqueName(authenticationToken, "ImportedCryptoToken" + caId, SoftCryptoToken.class.getName(), cryptoTokenProperties, baos.toByteArray(), authCode); } catch (NoSuchSlotException e1) { throw new RuntimeException( "Attempte to define a slot for a soft crypto token. This should not happen."); } final CAToken catoken = new CAToken(cryptoTokenId, caTokenProperties); // If this is a CVC CA we need to find out the sequence String sequence = CAToken.DEFAULT_KEYSEQUENCE; if (cacert instanceof CardVerifiableCertificate) { CardVerifiableCertificate cvccacert = (CardVerifiableCertificate) cacert; log.debug("Getting sequence from holderRef in CV certificate."); try { sequence = cvccacert.getCVCertificate().getCertificateBody().getHolderReference().getSequence(); } catch (NoSuchFieldException e) { log.error("Can not get sequence from holderRef in CV certificate, using default sequence."); } } log.debug("Setting sequence " + sequence); catoken.setKeySequence(sequence); log.debug("Setting default sequence format " + StringTools.KEY_SEQUENCE_FORMAT_NUMERIC); catoken.setKeySequenceFormat(StringTools.KEY_SEQUENCE_FORMAT_NUMERIC); catoken.setSignatureAlgorithm(signatureAlgorithm); catoken.setEncryptionAlgorithm(encryptionAlgorithm); return catoken; } catch (KeyStoreException e) { throw new IllegalCryptoTokenException(e); } catch (NoSuchProviderException e) { throw new IllegalCryptoTokenException(e); } catch (NoSuchAlgorithmException e) { throw new IllegalCryptoTokenException(e); } catch (CertificateException e) { throw new IllegalCryptoTokenException(e); } catch (IOException e) { throw new IllegalCryptoTokenException(e); } catch (IllegalStateException e) { throw new IllegalCryptoTokenException(e); } catch (InvalidAlgorithmParameterException e) { throw new IllegalCryptoTokenException(e); } catch (CryptoTokenOfflineException e) { throw new IllegalCryptoTokenException(e); } }
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 w w . ja va 2 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.ejbca.core.protocol.ocsp.ProtocolOcspHttpTest.java
/** * adds a CA Using ECDSA keys to the database. * * It also checks that the CA is stored correctly. * * @throws Exception//from w w w .j a v a 2 s. com * error */ private CAInfo addECDSACA(String dn, String keySpec) throws Exception { log.trace(">addECDSACA()"); boolean ret = false; int cryptoTokenId = 0; CAInfo info = null; try { cryptoTokenId = CryptoTokenTestUtils.createCryptoTokenForCA(admin, dn, keySpec); final CAToken catoken = CaTestUtils.createCaToken(cryptoTokenId, AlgorithmConstants.SIGALG_SHA256_WITH_ECDSA, AlgorithmConstants.SIGALG_SHA1_WITH_RSA); // Create and active OSCP CA Service. List<ExtendedCAServiceInfo> extendedcaservices = new ArrayList<ExtendedCAServiceInfo>(); extendedcaservices.add(new HardTokenEncryptCAServiceInfo(ExtendedCAServiceInfo.STATUS_ACTIVE)); extendedcaservices.add(new KeyRecoveryCAServiceInfo(ExtendedCAServiceInfo.STATUS_ACTIVE)); List<CertificatePolicy> policies = new ArrayList<CertificatePolicy>(1); policies.add(new CertificatePolicy("2.5.29.32.0", "", "")); X509CAInfo cainfo = new X509CAInfo(dn, dn, CAConstants.CA_ACTIVE, CertificateProfileConstants.CERTPROFILE_FIXED_ROOTCA, 365, CAInfo.SELFSIGNED, null, catoken); cainfo.setDescription("JUnit ECDSA CA"); cainfo.setPolicies(policies); cainfo.setExtendedCAServiceInfos(extendedcaservices); caAdminSession.createCA(admin, cainfo); info = caSession.getCAInfo(admin, dn); X509Certificate cert = (X509Certificate) info.getCertificateChain().iterator().next(); assertTrue("Error in created ca certificate", cert.getSubjectDN().toString().equals(dn)); assertTrue("Creating CA failed", info.getSubjectDN().equals(dn)); // Make BC cert instead to make sure the public key is BC provider type (to make our test below easier) X509Certificate bccert = (X509Certificate) CertTools.getCertfromByteArray(cert.getEncoded()); PublicKey pk = bccert.getPublicKey(); if (pk instanceof JCEECPublicKey) { JCEECPublicKey ecpk = (JCEECPublicKey) pk; assertEquals(ecpk.getAlgorithm(), "EC"); org.bouncycastle.jce.spec.ECParameterSpec spec = ecpk.getParameters(); if (StringUtils.equals(keySpec, "implicitlyCA")) { assertNull("ImplicitlyCA must have null spec", spec); } else { assertNotNull("secp256r1 must not have null spec", spec); } } else if (pk instanceof BCECPublicKey) { BCECPublicKey ecpk = (BCECPublicKey) pk; assertEquals(ecpk.getAlgorithm(), "EC"); org.bouncycastle.jce.spec.ECParameterSpec spec = ecpk.getParameters(); if (StringUtils.equals(keySpec, "implicitlyCA")) { assertNull("ImplicitlyCA must have null spec", spec); } else { assertNotNull("secp256r1 must not have null spec", spec); } } else { assertTrue("Public key is not EC: " + pk.getClass().getName(), false); } ret = true; } catch (CAExistsException pee) { log.info("CA exists."); } assertTrue("Creating ECDSA CA failed", ret); log.trace("<addECDSACA()"); return info; }
From source file:org.ejbca.util.CertTools.java
public static X509Certificate genSelfCertForPurpose(String dn, long validity, String policyId, PrivateKey privKey, PublicKey pubKey, String sigAlg, boolean isCA, int keyusage, String provider) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, CertificateEncodingException, IllegalStateException, NoSuchProviderException { // Create self signed certificate Date firstDate = new Date(); // Set back startdate ten minutes to avoid some problems with wrongly set clocks. firstDate.setTime(firstDate.getTime() - (10 * 60 * 1000)); Date lastDate = new Date(); // validity in days = validity*24*60*60*1000 milliseconds lastDate.setTime(lastDate.getTime() + (validity * (24 * 60 * 60 * 1000))); X509V3CertificateGenerator certgen = new X509V3CertificateGenerator(); // Transform the PublicKey to be sure we have it in a format that the X509 certificate generator handles, it might be // a CVC public key that is passed as parameter PublicKey publicKey = null;// w w w .j a va2 s . com if (pubKey instanceof RSAPublicKey) { RSAPublicKey rsapk = (RSAPublicKey) pubKey; RSAPublicKeySpec rSAPublicKeySpec = new RSAPublicKeySpec(rsapk.getModulus(), rsapk.getPublicExponent()); try { publicKey = KeyFactory.getInstance("RSA").generatePublic(rSAPublicKeySpec); } catch (InvalidKeySpecException e) { log.error("Error creating RSAPublicKey from spec: ", e); publicKey = pubKey; } } else if (pubKey instanceof ECPublicKey) { ECPublicKey ecpk = (ECPublicKey) pubKey; try { ECPublicKeySpec ecspec = new ECPublicKeySpec(ecpk.getW(), ecpk.getParams()); // will throw NPE if key is "implicitlyCA" publicKey = KeyFactory.getInstance("EC").generatePublic(ecspec); } catch (InvalidKeySpecException e) { log.error("Error creating ECPublicKey from spec: ", e); publicKey = pubKey; } catch (NullPointerException e) { log.debug("NullPointerException, probably it is implicitlyCA generated keys: " + e.getMessage()); publicKey = pubKey; } } else { log.debug("Not converting key of class. " + pubKey.getClass().getName()); publicKey = pubKey; } // Serialnumber is random bits, where random generator is initialized with Date.getTime() when this // bean is created. byte[] serno = new byte[8]; SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); random.setSeed(new Date().getTime()); random.nextBytes(serno); certgen.setSerialNumber(new java.math.BigInteger(serno).abs()); certgen.setNotBefore(firstDate); certgen.setNotAfter(lastDate); certgen.setSignatureAlgorithm(sigAlg); certgen.setSubjectDN(CertTools.stringToBcX509Name(dn)); certgen.setIssuerDN(CertTools.stringToBcX509Name(dn)); certgen.setPublicKey(publicKey); // Basic constranits is always critical and MUST be present at-least in CA-certificates. BasicConstraints bc = new BasicConstraints(isCA); certgen.addExtension(X509Extensions.BasicConstraints.getId(), true, bc); // Put critical KeyUsage in CA-certificates if (isCA) { X509KeyUsage ku = new X509KeyUsage(keyusage); certgen.addExtension(X509Extensions.KeyUsage.getId(), true, ku); } // Subject and Authority key identifier is always non-critical and MUST be present for certificates to verify in Firefox. try { if (isCA) { SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(publicKey.getEncoded())) .readObject()); SubjectKeyIdentifier ski = new SubjectKeyIdentifier(spki); SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(publicKey.getEncoded())) .readObject()); AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki); certgen.addExtension(X509Extensions.SubjectKeyIdentifier.getId(), false, ski); certgen.addExtension(X509Extensions.AuthorityKeyIdentifier.getId(), false, aki); } } catch (IOException e) { // do nothing } // CertificatePolicies extension if supplied policy ID, always non-critical if (policyId != null) { PolicyInformation pi = new PolicyInformation(new DERObjectIdentifier(policyId)); DERSequence seq = new DERSequence(pi); certgen.addExtension(X509Extensions.CertificatePolicies.getId(), false, seq); } X509Certificate selfcert = certgen.generate(privKey, provider); return selfcert; }
From source file:org.ejbca.util.keystore.KeyTools.java
/** Testing a key pair to verify that it is possible to first sign and then verify with it. * /*from w w w . java 2 s . c o m*/ * @param priv private key to sign a string with * @param pub public key to verify the signature with * @param provider A provider used for signing with the private key, or null if "BC" should be used. * * @throws InvalidKeyException if the public key can not be used to verify a string signed by the private key, because the key is wrong or the signature operation fails for other reasons such as a NoSuchAlgorithmException or SignatureException. * @throws NoSuchProviderException if the provider is not installed. */ public static void testKey(final PrivateKey priv, final PublicKey pub, final String provider) throws InvalidKeyException, NoSuchProviderException { final byte input[] = "Lillan gick pa vagen ut, motte dar en katt...".getBytes(); final byte signBV[]; final String testSigAlg; { final Iterator<String> i = AlgorithmTools.getSignatureAlgorithms(pub).iterator(); final String tmp = i.hasNext() ? i.next() : null; testSigAlg = tmp != null ? tmp : "SHA1WithRSA"; } if (log.isDebugEnabled()) { log.debug("Testing keys with algorithm: " + pub.getAlgorithm()); log.debug("testSigAlg: " + testSigAlg); log.debug("provider: " + provider); log.trace("privateKey: " + priv); log.trace("privateKey class: " + priv.getClass().getName()); log.trace("publicKey: " + pub); log.trace("publicKey class: " + pub.getClass().getName()); } try { { final Provider prov = Security.getProvider(provider != null ? provider : "BC"); final Signature signature = Signature.getInstance(testSigAlg, prov); signature.initSign(priv); signature.update(input); signBV = signature.sign(); if (signBV == null) { throw new InvalidKeyException("Result from signing is null."); } if (log.isDebugEnabled()) { log.trace("Created signature of size: " + signBV.length); log.trace("Created signature: " + new String(Hex.encode(signBV))); } } { final Signature signature = Signature.getInstance(testSigAlg, "BC"); signature.initVerify(pub); signature.update(input); if (!signature.verify(signBV)) { throw new InvalidKeyException("Not possible to sign and then verify with key pair."); } } } catch (NoSuchAlgorithmException e) { throw new InvalidKeyException("Exception testing key: " + e.getMessage(), e); } catch (SignatureException e) { throw new InvalidKeyException("Exception testing key: " + e.getMessage(), e); } }