List of usage examples for java.security.cert Certificate getPublicKey
public abstract PublicKey getPublicKey();
From source file:org.ejbca.core.ejb.ca.store.CertificateStoreSessionBean.java
@TransactionAttribute(TransactionAttributeType.REQUIRED) @Override/*from ww w .j a va2s .c om*/ public boolean storeCertificate(Admin admin, Certificate incert, String username, String cafp, int status, int type, int certificateProfileId, String tag, long updateTime) throws CreateException { if (log.isTraceEnabled()) { log.trace(">storeCertificate(" + username + ", " + cafp + ", " + status + ", " + type + ")"); } // Strip dangerous chars username = StringTools.strip(username); // We need special handling here of CVC certificate with EC keys, because they lack EC parameters in all certs except the Root certificate (CVCA) PublicKey pubk = incert.getPublicKey(); if ((pubk instanceof PublicKeyEC)) { PublicKeyEC pkec = (PublicKeyEC) pubk; // The public key of IS and DV certificate (CVC) do not have any parameters so we have to do some magic to get a complete EC public key ECParameterSpec spec = pkec.getParams(); if (spec == null) { // We need to enrich this public key with parameters try { if (cafp != null) { String cafingerp = cafp; CertificateData cacert = CertificateData.findByFingerprint(entityManager, cafp); if (cacert == null) { throw new FinderException(); } String nextcafp = cacert.getCaFingerprint(); int bar = 0; // never go more than 5 rounds, who knows what strange things can exist in the CAFingerprint column, make sure we never get stuck here while ((!StringUtils.equals(cafingerp, nextcafp)) && (bar++ < 5)) { cacert = CertificateData.findByFingerprint(entityManager, cafp); if (cacert == null) { throw new FinderException(); } cafingerp = nextcafp; nextcafp = cacert.getCaFingerprint(); } // We found a root CA certificate, hopefully ? PublicKey pkwithparams = cacert.getCertificate().getPublicKey(); pubk = KeyTools.getECPublicKeyWithParams(pubk, pkwithparams); } } catch (FinderException e) { log.info("Can not find CA certificate with fingerprint: " + cafp); } catch (Exception e) { // This catches NoSuchAlgorithmException, NoSuchProviderException and InvalidKeySpecException and possibly something else (NPE?) // because we want to continue anyway if (log.isDebugEnabled()) { log.debug("Can not enrich EC public key with missing parameters: ", e); } } } } // finished with ECC key special handling // Create the certificate in one go with all parameters at once. This used to be important in EJB2.1 so the persistence layer only creates *one* single // insert statement. If we do a home.create and the some setXX, it will create one insert and one update statement to the database. // Probably not important in EJB3 anymore final CertificateData data1 = new CertificateData(incert, pubk, username, cafp, status, type, certificateProfileId, tag, updateTime); final String issuerDN = data1.getIssuerDN(); try { entityManager.persist(data1); } catch (Exception e) { // For backward compatibility. We should drop the throw entirely and rely on the return value. CreateException ce = new CreateException(); ce.setStackTrace(e.getStackTrace()); throw ce; } final String msg = intres.getLocalizedMessage("store.storecert"); logSession.log(admin, issuerDN.hashCode(), LogConstants.MODULE_CA, new Date(), username, incert, LogConstants.EVENT_INFO_STORECERTIFICATE, msg); log.trace("<storeCertificate()"); return true; }
From source file:org.ejbca.ui.cli.HSMKeyTool.java
private static boolean doIt(final String[] orgArgs) throws Exception { // Get and remove optional switches final List<String> argsList = CliTools.getAsModifyableList(orgArgs); final KeyStore.ProtectionParameter protectionParameter; final String password = CliTools.getAndRemoveParameter("-password", argsList); if (password != null) { protectionParameter = new KeyStore.PasswordProtection(password.toCharArray()); } else {// w ww. ja va 2 s .c om protectionParameter = null; } final String[] args = CliTools.getAsArgs(argsList); if (args[1].toLowerCase().trim().contains(GENERATE_BATCH_SWITCH)) { if (args.length < 4) { printCommandString(args, "<name of batch file> [", TOKEN_ID_PARAM, "]"); printTokenIdDescription(); sunConfigFileUseDescription(); System.err.println( "The batch file is a file which specifies alias and key specification for each key to be generated."); System.err .println("Each row is starting with a key alias then the key specification is following."); System.err.println("The specification of the key is done like this: " + KEY_SPEC_DESC); tooFewArguments(args); } final String storeId; final Pkcs11SlotLabelType slotType; if (args.length > 4) { storeId = trimStoreId(args[4]); slotType = getTokenLabelType(args[4]); } else { storeId = null; slotType = Pkcs11SlotLabelType.SUN_FILE; } final KeyStoreTools store = KeyStoreToolsFactory.getInstance(args[2], storeId, slotType, null, protectionParameter, "batch-" + new Date().getTime()); generateBatch(args[3], store); return true; } if (args[1].toLowerCase().trim().contains(GENERATE_SWITCH)) { if (args.length < 4) { printCommandString(args, Character.valueOf('<'), KEY_SPEC_DESC, "> <key entry name> [", TOKEN_ID_PARAM, "]"); printTokenIdDescription(); sunConfigFileUseDescription(); tooFewArguments(args); } final String keyEntryName = args.length > 4 ? args[4] : "myKey"; final String storeId; final Pkcs11SlotLabelType slotType; if (args.length > 5) { storeId = trimStoreId(args[5]); slotType = getTokenLabelType(args[5]); } else { storeId = null; slotType = Pkcs11SlotLabelType.SUN_FILE; } System.out.println("Using Slot Reference Type: " + slotType + '.'); final KeyStoreTools store = KeyStoreToolsFactory.getInstance(args[2], storeId, slotType, null, protectionParameter, "priv-" + keyEntryName); store.generateKeyPair(args[3], keyEntryName); System.out.println("Created certificate with entry " + keyEntryName + '.'); return true; } if (args[1].toLowerCase().trim().equals(DELETE_SWITCH)) { if (args.length < 4) { printCommandString(args, TOKEN_ID_PARAM, " [<key entry name>]"); printTokenIdDescription(); tooFewArguments(args); } final String alias = args.length > 4 ? args[4] : null; System.out.println("Deleting certificate with alias " + alias + '.'); final String storeId = trimStoreId(args[3]); final Pkcs11SlotLabelType slotType = getTokenLabelType(args[3]); KeyStoreToolsFactory.getInstance(args[2], storeId, slotType, null, protectionParameter) .deleteEntry(alias); return true; } if (args[1].toLowerCase().trim().equals(CERT_REQ)) { // First we check if we have a switch for "-explicitecc" for explicit ecc parameters used in ICAO epassports. final List<String> argsListLocal = CliTools.getAsModifyableList(args); final boolean explicitEccParameters = argsListLocal.remove("-explicitecc"); final boolean forAllKeys = argsListLocal.remove("-all"); final String modArgs[] = argsListLocal.toArray(new String[argsListLocal.size()]); if (modArgs.length < 4 || (modArgs.length < 5 && !forAllKeys)) { printCommandString(args, TOKEN_ID_PARAM, " <key entry name> [<CN>] [-explicitecc]"); printCommandString(args, TOKEN_ID_PARAM, " [-all] [-explicitecc]"); printTokenIdDescription(); tooFewArguments(modArgs); } final String storeId = trimStoreId(modArgs[3]); final Pkcs11SlotLabelType slotType = getTokenLabelType(modArgs[3]); final KeyStoreTools container = KeyStoreToolsFactory.getInstance(modArgs[2], storeId, slotType, null, protectionParameter); final List<String> entries; if (forAllKeys) { entries = new LinkedList<>(); final CachingKeyStoreWrapper ks = container.getKeyStore(); final Enumeration<String> aliases = ks.aliases(); while (aliases.hasMoreElements()) { final String alias = aliases.nextElement(); if (ks.isKeyEntry(alias)) { entries.add(alias); } } } else { entries = Collections.singletonList(modArgs[4]); } for (String entry : entries) { container.generateCertReq(entry, modArgs.length > 5 ? modArgs[5] : null, explicitEccParameters); } return true; } if (args[1].toLowerCase().trim().equals(INSTALL_CERT)) { if (args.length < 5) { printCommandString(args, TOKEN_ID_PARAM, " <certificate chain files in PEM format (one chain per file)>"); printTokenIdDescription(); tooFewArguments(args); } final String storeId = trimStoreId(args[3]); final Pkcs11SlotLabelType slotType = getTokenLabelType(args[3]); final KeyStoreTools container = KeyStoreToolsFactory.getInstance(args[2], storeId, slotType, null, protectionParameter); boolean failure = false; for (int i = 4; i < args.length; i++) { try { container.installCertificate(args[i]); } catch (Exception ex) { failure = true; log.error("File " + args[i] + " failed.", ex); } } if (failure) { throw new Exception("At least one certificate could not be installed. See the log for more info."); } return true; } if (args[1].toLowerCase().trim().equals(INSTALL_TRUSTED_ROOT)) { if (args.length < 5) { printCommandString(args, TOKEN_ID_PARAM, " <trusted root certificate in PEM format>"); printTokenIdDescription(); tooFewArguments(args); } final String storeId = trimStoreId(args[3]); final Pkcs11SlotLabelType slotType = getTokenLabelType(args[3]); KeyStoreToolsFactory.getInstance(args[2], storeId, slotType, null, protectionParameter) .installTrustedRoot(args[4]); return true; } if (args[1].toLowerCase().trim().equals(ENCRYPT_SWITCH)) { String symmAlgOid = CMSEnvelopedGenerator.AES128_CBC; if (args.length < 5) { System.err.println("There are two ways of doing the encryption:"); printCommandString(args, TOKEN_ID_PARAM, " <input file> <output file> <key alias> [optional symm algorithm oid]"); printCommandStringNoSharedLib(args, "<input file> <output file> <file with certificate with public key to use> [optional symm algorithm oid]"); printTokenIdDescription(); System.err.println( "Optional symmetric encryption algorithm OID can be for example 2.16.840.1.101.3.4.1.42 (AES256_CBC) or 1.2.392.200011.61.1.1.1.4 (CAMELLIA256_CBC). Default is to use AES256_CBC."); tooFewArguments(args); } if (args.length < 7) { Security.addProvider(new BouncyCastleProvider()); if (args.length > 5) { // We have a symmAlg as last parameter symmAlgOid = args[5]; } System.out.println("Using symmetric encryption algorithm: " + symmAlgOid); try (final InputStream certIS = new FileInputStream(args[4]); final InputStream is = new FileInputStream(args[2]); final OutputStream os = new FileOutputStream(args[3])) { final X509Certificate cert = (X509Certificate) CertificateFactory.getInstance("X.509") .generateCertificate(new BufferedInputStream(certIS)); CMS.encrypt(is, os, cert, symmAlgOid); } } else { if (args.length > 7) { // We have a symmAlg as last parameter symmAlgOid = args[7]; } System.out.println("Using symmstric encryption algorithm: " + symmAlgOid); final String storeId = trimStoreId(args[3]); final Pkcs11SlotLabelType slotType = getTokenLabelType(args[3]); try (final InputStream is = new FileInputStream(args[4]); final OutputStream os = new FileOutputStream(args[5]);) { final Certificate cert = KeyStoreToolsFactory .getInstance(args[2], storeId, slotType, null, protectionParameter).getKeyStore() .getCertificate(args[6]); CMS.encrypt(is, os, (X509Certificate) cert, symmAlgOid); } } return true; } if (args[1].toLowerCase().trim().equals(DECRYPT_SWITCH)) { if (args.length < 7) { printCommandString(args, TOKEN_ID_PARAM, " <input file> <output file> <key alias>"); printTokenIdDescription(); tooFewArguments(args); } final String storeId = trimStoreId(args[3]); final Pkcs11SlotLabelType slotType = getTokenLabelType(args[3]); try (final InputStream is = new FileInputStream(args[4]); final OutputStream os = new FileOutputStream(args[5])) { final KeyStoreTools keyStore = KeyStoreToolsFactory.getInstance(args[2], storeId, slotType, null, protectionParameter); CMS.decrypt(is, os, (PrivateKey) keyStore.getKeyStore().getKey(args[6], null), keyStore.getProviderName()); } return true; } if (args[1].toLowerCase().trim().equals(SIGN_SWITCH)) { if (args.length < 7) { printCommandString(args, TOKEN_ID_PARAM, " <input file> <output file> <key alias>"); printTokenIdDescription(); tooFewArguments(args); } final String storeId = trimStoreId(args[3]); final Pkcs11SlotLabelType slotType = getTokenLabelType(args[3]); final KeyStoreTools keyStore = KeyStoreToolsFactory.getInstance(args[2], storeId, slotType, null, protectionParameter); final String alias = args[6]; final PrivateKey key = (PrivateKey) keyStore.getKeyStore().getKey(alias, null); final X509Certificate cert = (X509Certificate) keyStore.getKeyStore().getCertificate(alias); try (final InputStream is = new FileInputStream(args[4]); final OutputStream os = new FileOutputStream(args[5]);) { CMS.sign(is, os, key, keyStore.getProviderName(), cert); } return true; } if (args[1].toLowerCase().trim().equals(LINKCERT_SWITCH)) { if (args.length < 8) { printCommandString(args, TOKEN_ID_PARAM, " <old ca-cert> <new ca-cert> <output link-cert> <key alias> [<sig alg override>]"); printTokenIdDescription(); System.err.println(); System.err.println("Creates a link certificate that links the old and new certificate files."); System.err.println("You should use this command with the old HSM key. It does not need any"); System.err.println("access to the new key."); System.err.println(); tooFewArguments(args); } final String storeId = trimStoreId(args[3]); final Pkcs11SlotLabelType slotType = getTokenLabelType(args[3]); final KeyStoreTools ksc = KeyStoreToolsFactory.getInstance(args[2], storeId, slotType, null, protectionParameter); final String alias = args[7]; final String oldCertPath = args[4]; final String newCertPath = args[5]; final String outputPath = args[6]; final String signProviderName = ksc.getProviderName(); final String sigAlgOverride = (args.length > 8 ? args[8] : "null"); // Parse certificates final byte[] oldCertBytes; try (final InputStream is = new FileInputStream(oldCertPath)) { oldCertBytes = IOUtils.toByteArray(is); } final byte[] newCertBytes; try (final InputStream is = new FileInputStream(newCertPath)) { newCertBytes = IOUtils.toByteArray(is); } final Certificate oldCert = CertTools.getCertfromByteArray(oldCertBytes, BouncyCastleProvider.PROVIDER_NAME, Certificate.class); final Certificate newCert = CertTools.getCertfromByteArray(newCertBytes, BouncyCastleProvider.PROVIDER_NAME, Certificate.class); final boolean isCVCA = (oldCert instanceof CardVerifiableCertificate); if (isCVCA != (newCert instanceof CardVerifiableCertificate)) { log.error("Error: Old and new certificates are not of the same type (X509 / CVC)"); return true; // = valid command-line syntax } System.out.println("Type of certificates: " + (isCVCA ? "CVC" : "X509")); // Detect name change final String oldDN = CertTools.getSubjectDN(oldCert); final String newDN = CertTools.getSubjectDN(newCert); System.out.println("Old DN: " + oldDN); System.out.println("New DN: " + newDN); final boolean nameChange; if (!oldDN.equals(newDN)) { if (isCVCA) { System.out.println("Name change detected."); } else { System.out.println("Name change detected. Will add Name Change extension."); } nameChange = true; } else { System.out.println("No name change detected."); nameChange = false; } final ByteArrayOutputStream baos = new ByteArrayOutputStream(); // Get new and old key final PublicKey newPubKey = newCert.getPublicKey(); if (newPubKey == null) { System.err.println("Error: Failed to extract public key from new certificate"); return true; } final Key oldKey = ksc.getKeyStore().getKey(alias, null); if (oldKey == null) { System.err.println("Error: Could not find the key named " + alias); return true; } final PrivateKey oldPrivKey = (PrivateKey) oldKey; if (isCVCA) { final CVCertificate oldCertCVC = ((CardVerifiableCertificate) oldCert).getCVCertificate(); final CVCertificate newCertCVC = ((CardVerifiableCertificate) newCert).getCVCertificate(); final String linkSigAlg; if (sigAlgOverride.equalsIgnoreCase("null")) { final OIDField oldKeyTypeOid = oldCertCVC.getCertificateBody().getPublicKey() .getObjectIdentifier(); linkSigAlg = AlgorithmUtil.getAlgorithmName(oldKeyTypeOid); } else { System.err.println("Error: Overriding the signature algorithm is not supported for CVC"); return true; } System.out.println("Using signature algorithm " + linkSigAlg); final HolderReferenceField caHolder = oldCertCVC.getCertificateBody().getHolderReference(); final CAReferenceField caRef = new CAReferenceField(caHolder.getCountry(), caHolder.getMnemonic(), caHolder.getSequence()); final HolderReferenceField certHolder = newCertCVC.getCertificateBody().getHolderReference(); final AuthorizationRole authRole = newCertCVC.getCertificateBody().getAuthorizationTemplate() .getAuthorizationField().getAuthRole(); final AccessRights rights = newCertCVC.getCertificateBody().getAuthorizationTemplate() .getAuthorizationField().getAccessRights(); final Date validFrom = new Date(new Date().getTime() - 60L * 15L * 1000L); // back date by 15 minutes to allow for clock skew final Date validTo = oldCertCVC.getCertificateBody().getValidTo(); final CVCertificate linkCert = CertificateGenerator.createCertificate(newPubKey, oldPrivKey, linkSigAlg, caRef, certHolder, authRole, rights, validFrom, validTo, signProviderName); try (final DataOutputStream dos = new DataOutputStream(baos)) { linkCert.encode(dos); } } else { // X509 CA final X509Certificate oldCertX509 = (X509Certificate) oldCert; final X509Certificate newCertX509 = (X509Certificate) newCert; final String linkSigAlg; if (sigAlgOverride.equalsIgnoreCase("null")) { // Actually, we should use signature algorithm of new cert if the old key allows that. // Instead of doing that we allow the user to manually override the signature algorithm if needed. linkSigAlg = oldCertX509.getSigAlgName(); } else { System.err.println("Warning: Signature algorithm manually overridden!"); linkSigAlg = sigAlgOverride; } System.out.println("Using signature algorithm " + linkSigAlg); final BigInteger serno = SernoGeneratorRandom.instance().getSerno(); final SubjectPublicKeyInfo pkinfo = SubjectPublicKeyInfo.getInstance(newPubKey.getEncoded()); final Date validFrom = new Date(new Date().getTime() - 60L * 15L * 1000L); // back date by 15 minutes to allow for clock skew final Date validTo = oldCertX509.getNotAfter(); final X500Name oldDNName = X500Name.getInstance(oldCertX509.getSubjectX500Principal().getEncoded()); final X500Name newDNName = X500Name.getInstance(newCertX509.getSubjectX500Principal().getEncoded()); final X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder(oldDNName, serno, validFrom, validTo, newDNName, pkinfo); // Copy all extensions except AKID final ExtensionsGenerator extgen = new ExtensionsGenerator(); final Set<String> oids = new LinkedHashSet<>(); final Set<String> criticalOids = newCertX509.getCriticalExtensionOIDs(); oids.addAll(criticalOids); oids.addAll(newCertX509.getNonCriticalExtensionOIDs()); for (final String extOidStr : oids) { final ASN1ObjectIdentifier extoid = new ASN1ObjectIdentifier(extOidStr); if (!extoid.equals(Extension.authorityKeyIdentifier)) { final byte[] extbytes = newCertX509.getExtensionValue(extOidStr); final ASN1OctetString str = (ASN1OctetString) ASN1Primitive.fromByteArray(extbytes); extgen.addExtension(extoid, criticalOids.contains(extOidStr), ASN1Primitive.fromByteArray(str.getOctets())); } } if (nameChange) { // id-icao-mrtd-security-extensions-nameChange = 2.23.136.1.1.6.1 extgen.addExtension(ICAOObjectIdentifiers.id_icao_extensions_namechangekeyrollover, false, DERNull.INSTANCE); } // Some checks if (newCertX509.getExtensionValue(Extension.subjectKeyIdentifier.getId()) == null) { System.err.println( "Warning: Certificate of new CSCA is missing the Subject Key Identifier extension, which is mandatory."); } if (newCertX509.getExtensionValue(Extension.authorityKeyIdentifier.getId()) == null) { System.err.println( "Warning: Certificate of new CSCA is missing the Authority Key Identifier extension, which is mandatory."); } // If the new cert has an AKID, then add that extension but with the key id value of the old cert final byte[] oldSKIDBytes = oldCertX509.getExtensionValue(Extension.subjectKeyIdentifier.getId()); if (oldSKIDBytes != null) { final ASN1OctetString str = (ASN1OctetString) ASN1Primitive.fromByteArray(oldSKIDBytes); final ASN1OctetString innerStr = (ASN1OctetString) ASN1Primitive.fromByteArray(str.getOctets()); final AuthorityKeyIdentifier akidExt = new AuthorityKeyIdentifier(innerStr.getOctets()); extgen.addExtension(Extension.authorityKeyIdentifier, false, akidExt); } else { System.err.println( "Warning: The old certificate doesn't have any SubjectKeyIdentifier. The link certificate will not have any AuthorityKeyIdentifier."); } // Add extensions to the certificate final Extensions exts = extgen.generate(); for (final ASN1ObjectIdentifier extoid : exts.getExtensionOIDs()) { final Extension ext = exts.getExtension(extoid); certbuilder.addExtension(extoid, ext.isCritical(), ext.getParsedValue()); } // Sign the certificate final ContentSigner signer = new BufferingContentSigner( new JcaContentSignerBuilder(linkSigAlg).setProvider(signProviderName).build(oldPrivKey), 20480); final X509CertificateHolder certHolder = certbuilder.build(signer); baos.write(certHolder.getEncoded()); // Save to output file try (final FileOutputStream fos = new FileOutputStream(outputPath)) { baos.writeTo(fos); } } return true; } if (args[1].toLowerCase().trim().equals(VERIFY_SWITCH)) { final CMS.VerifyResult verifyResult; if (args.length < 5) { System.err.println("There are two ways of doing the encryption:"); printCommandString(args, TOKEN_ID_PARAM, " <input file> <output file> <key alias>"); printTokenIdDescription(); printCommandStringNoSharedLib(args, "<input file> <output file> <file with certificate with public key to use>"); tooFewArguments(args); } if (args.length < 7) { Security.addProvider(new BouncyCastleProvider()); try (final InputStream certIS = new FileInputStream(args[4]); final InputStream is = new FileInputStream(args[2]); final OutputStream os = new FileOutputStream(args[3]);) { final X509Certificate cert = (X509Certificate) CertificateFactory.getInstance("X.509") .generateCertificate(new BufferedInputStream(certIS)); verifyResult = CMS.verify(is, os, cert); } } else { final String storeId = trimStoreId(args[3]); final Pkcs11SlotLabelType slotType = getTokenLabelType(args[3]); final KeyStoreTools keyStore = KeyStoreToolsFactory.getInstance(args[2], storeId, slotType, null, protectionParameter); final X509Certificate cert = (X509Certificate) keyStore.getKeyStore().getCertificate(args[6]); try (final InputStream is = new FileInputStream(args[4]); final OutputStream os = new FileOutputStream(args[5])) { verifyResult = CMS.verify(is, os, cert); } } if (verifyResult == null) { System.err.println("Not possible to parse signed file."); System.exit(4); // Not verifying // NOPMD, it's not a JEE app return false;//will never be executes. just to avoid warning. } System.out.println( "The signature of the input " + (verifyResult.isVerifying ? "has been" : "could not be") + " verified. The file was signed on '" + verifyResult.signDate + "'. The public part of the signing key is in a certificate with serial number " + verifyResult.signerId.getSerialNumber() + " issued by '" + verifyResult.signerId.getIssuer() + "'."); if (!verifyResult.isVerifying) { System.exit(4); // Not verifying // NOPMD, it's not a JEE app } return true; } if (args[1].toLowerCase().trim().equals(TEST_SWITCH)) { if (args.length < 4) { printCommandString(args, TOKEN_ID_PARAM, " [<'m:n' m # of threads, n # of tests>] [<alias for stress test>] [<type of stress test>]"); printTokenIdDescription(); System.err.println( " If a file named \"./testData\" exists then the data that is signed, is read from this file."); tooFewArguments(args); } final String storeId = trimStoreId(args[3]); final Pkcs11SlotLabelType slotType = getTokenLabelType(args[3]); final NrOfThreadsAndNrOfTests notanot = new NrOfThreadsAndNrOfTests(args.length > 4 ? args[4] : null); KeyStoreContainerTest.test(args[2], storeId, slotType, notanot.threads, notanot.tests, args.length > 5 ? args[5].trim() : null, args.length > 6 ? args[6].trim() : null, protectionParameter); return true; } if (args[1].toLowerCase().trim().equals(RENAME)) { if (args.length < 6) { printCommandString(args, TOKEN_ID_PARAM, " <old key alias> <new key alias>"); printTokenIdDescription(); tooFewArguments(args); } final String storeId = trimStoreId(args[3]); final Pkcs11SlotLabelType slotType = getTokenLabelType(args[3]); final KeyStoreTools keyStore = KeyStoreToolsFactory.getInstance(args[2], storeId, slotType, null, protectionParameter); keyStore.renameEntry(args[4], args[5]); return true; } if (args[1].toLowerCase().trim().equals(MOVE_SWITCH)) { if (args.length < 5) { printCommandString(args, "<from PKCS#11 token identifier> <to PKCS#11 token identifier>"); printTokenIdDescription(); tooFewArguments(args); } final KeyStoreTools fromKS = KeyStoreToolsFactory.getInstance(args[2], trimStoreId(args[3]), getTokenLabelType(args[3]), null, protectionParameter); final KeyStoreTools toKS = KeyStoreToolsFactory.getInstance(args[2], trimStoreId(args[4]), getTokenLabelType(args[4]), null, protectionParameter); System.out.println("Moving entry with alias '" + args[3] + "' to alias '" + args[4] + '.'); final Enumeration<String> e = fromKS.getKeyStore().aliases(); while (e.hasMoreElements()) { final String alias = e.nextElement(); if (fromKS.getKeyStore().isKeyEntry(alias)) { final Key key = fromKS.getKeyStore().getKey(alias, null); final Certificate chain[] = fromKS.getKeyStore().getCertificateChain(alias); toKS.setKeyEntry(alias, key, chain); } fromKS.getKeyStore().deleteEntry(alias); } fromKS.getKeyStore().store(null, null); toKS.getKeyStore().store(null, null); return true; } return false; }
From source file:org.cesecore.certificates.certificate.CertificateStoreSessionBean.java
License:asdf
/** Local interface only */ @Override//from w w w . jav a 2 s . com @TransactionAttribute(TransactionAttributeType.REQUIRED) public CertificateDataWrapper storeCertificateNoAuth(AuthenticationToken adminForLogging, Certificate incert, String username, String cafp, int status, int type, int certificateProfileId, String tag, long updateTime) { if (log.isTraceEnabled()) { log.trace(">storeCertificateNoAuth(" + username + ", " + cafp + ", " + status + ", " + type + ")"); } final PublicKey pubk = enrichEcPublicKey(incert.getPublicKey(), cafp); // Create the certificate in one go with all parameters at once. This used to be important in EJB2.1 so the persistence layer only creates // *one* single // insert statement. If we do a home.create and the some setXX, it will create one insert and one update statement to the database. // Probably not important in EJB3 anymore final CertificateData data1; final boolean useBase64CertTable = CesecoreConfiguration.useBase64CertTable(); Base64CertData base64CertData = null; if (useBase64CertTable) { // use special table for encoded data if told so. base64CertData = new Base64CertData(incert); this.entityManager.persist(new Base64CertData(incert)); } data1 = new CertificateData(incert, pubk, username, cafp, status, type, certificateProfileId, tag, updateTime, useBase64CertTable); this.entityManager.persist(data1); final String serialNo = CertTools.getSerialNumberAsString(incert); final String msg = INTRES.getLocalizedMessage("store.storecert", username, data1.getFingerprint(), data1.getSubjectDN(), data1.getIssuerDN(), serialNo); Map<String, Object> details = new LinkedHashMap<String, Object>(); details.put("msg", msg); final String caId = String.valueOf(CertTools.getIssuerDN(incert).hashCode()); logSession.log(EventTypes.CERT_STORED, EventStatus.SUCCESS, ModuleTypes.CERTIFICATE, ServiceTypes.CORE, adminForLogging.toString(), caId, serialNo, username, details); if (log.isTraceEnabled()) { log.trace("<storeCertificateNoAuth()"); } return new CertificateDataWrapper(incert, data1, base64CertData); }
From source file:org.apache.hc.client5.http.impl.auth.CredSspScheme.java
@Override public String generateAuthResponse(final HttpHost host, final HttpRequest request, final HttpContext context) throws AuthenticationException { if (ntcredentials == null) { throw new AuthenticationException("NT credentials not available"); }// w ww .j a v a 2 s . c o m final String outputString; if (state == State.UNINITIATED) { beginTlsHandshake(); outputString = wrapHandshake(); state = State.TLS_HANDSHAKE; } else if (state == State.TLS_HANDSHAKE) { outputString = wrapHandshake(); } else if (state == State.TLS_HANDSHAKE_FINISHED) { final int ntlmFlags = getNtlmFlags(); final ByteBuffer buf = allocateOutBuffer(); type1Message = new NTLMEngineImpl.Type1Message(ntcredentials.getNetbiosDomain(), ntcredentials.getWorkstation(), ntlmFlags); final byte[] ntlmNegoMessageEncoded = type1Message.getBytes(); final CredSspTsRequest req = CredSspTsRequest.createNegoToken(ntlmNegoMessageEncoded); req.encode(buf); buf.flip(); outputString = wrap(buf); state = State.NEGO_TOKEN_SENT; } else if (state == State.NEGO_TOKEN_RECEIVED) { final ByteBuffer buf = allocateOutBuffer(); type2Message = new NTLMEngineImpl.Type2Message(lastReceivedTsRequest.getNegoToken()); final Certificate peerServerCertificate = getPeerServerCertificate(); type3Message = new NTLMEngineImpl.Type3Message(ntcredentials.getNetbiosDomain(), ntcredentials.getWorkstation(), ntcredentials.getUserName(), ntcredentials.getPassword(), type2Message.getChallenge(), type2Message.getFlags(), type2Message.getTarget(), type2Message.getTargetInfo(), peerServerCertificate, type1Message.getBytes(), type2Message.getBytes()); final byte[] ntlmAuthenticateMessageEncoded = type3Message.getBytes(); final byte[] exportedSessionKey = type3Message.getExportedSessionKey(); ntlmOutgoingHandle = new NTLMEngineImpl.Handle(exportedSessionKey, NTLMEngineImpl.Mode.CLIENT, true); ntlmIncomingHandle = new NTLMEngineImpl.Handle(exportedSessionKey, NTLMEngineImpl.Mode.SERVER, true); final CredSspTsRequest req = CredSspTsRequest.createNegoToken(ntlmAuthenticateMessageEncoded); peerPublicKey = getSubjectPublicKeyDer(peerServerCertificate.getPublicKey()); final byte[] pubKeyAuth = createPubKeyAuth(); req.setPubKeyAuth(pubKeyAuth); req.encode(buf); buf.flip(); outputString = wrap(buf); state = State.PUB_KEY_AUTH_SENT; } else if (state == State.PUB_KEY_AUTH_RECEIVED) { verifyPubKeyAuthResponse(lastReceivedTsRequest.getPubKeyAuth()); final byte[] authInfo = createAuthInfo(ntcredentials); final CredSspTsRequest req = CredSspTsRequest.createAuthInfo(authInfo); final ByteBuffer buf = allocateOutBuffer(); req.encode(buf); buf.flip(); outputString = wrap(buf); state = State.CREDENTIALS_SENT; } else { throw new AuthenticationException("Wrong state " + state); } return outputString; }
From source file:org.ejbca.util.CertTools.java
/** Simple method that looks at the certificate and determines, from EJBCA's standpoint, which signature algorithm it is * //from www .j a v a 2s . com * @param cert the cert to examine * @return Signature algorithm from AlgorithmConstants.SIGALG_SHA1_WITH_RSA etc. */ public static String getSignatureAlgorithm(Certificate cert) { String signatureAlgorithm = null; String certSignatureAlgorithm = getCertSignatureAlgorithmAsString(cert); // The signature strign returned from the certificate is often not usable as the signature algorithm we must // specify for a CA in EJBCA, for example SHA1WithECDSA is returned as only ECDSA, so we need some magic to fix it up. PublicKey publickey = cert.getPublicKey(); if (publickey instanceof RSAPublicKey) { boolean isMgf = true; if (certSignatureAlgorithm.indexOf("MGF") == -1) { isMgf = false; } if (certSignatureAlgorithm.indexOf("256") == -1) { boolean md5 = true; if (certSignatureAlgorithm.indexOf("MD5") == -1) { md5 = false; } if (isMgf) { signatureAlgorithm = AlgorithmConstants.SIGALG_SHA1_WITH_RSA_AND_MGF1; } else { if (md5) { signatureAlgorithm = AlgorithmConstants.SIGALG_MD5_WITH_RSA; } else { signatureAlgorithm = AlgorithmConstants.SIGALG_SHA1_WITH_RSA; } } } else { if (isMgf) { signatureAlgorithm = AlgorithmConstants.SIGALG_SHA256_WITH_RSA_AND_MGF1; } else { signatureAlgorithm = AlgorithmConstants.SIGALG_SHA256_WITH_RSA; } } } else if (publickey instanceof DSAPublicKey) { signatureAlgorithm = AlgorithmConstants.SIGALG_SHA1_WITH_DSA; } else { if (certSignatureAlgorithm.indexOf("256") != -1) { signatureAlgorithm = AlgorithmConstants.SIGALG_SHA256_WITH_ECDSA; } else if (certSignatureAlgorithm.indexOf("224") != -1) { signatureAlgorithm = AlgorithmConstants.SIGALG_SHA224_WITH_ECDSA; } else { signatureAlgorithm = AlgorithmConstants.SIGALG_SHA1_WITH_ECDSA; } } log.debug("getSignatureAlgorithm: " + signatureAlgorithm); return signatureAlgorithm; }
From source file:com.threerings.getdown.data.Application.java
/** * Downloads a new copy of the specified control file, optionally validating its signature. * If the download is successful, moves it over the old file on the filesystem. * * <p> We implement simple signing of the digest.txt file for use with the Getdown applet, but * this should never be used as-is with a non-applet getdown installation, as the signing * format has no provisions for declaring arbitrary signing key IDs, signature algorithm, et al * -- it is entirely reliant on the ability to upgrade the Getdown applet, and its signature * validation implementation, at-will (ie, via an Applet). * * <p> TODO: Switch to PKCS #7 or CMS. *//* w w w.j ava2s . c om*/ protected void downloadControlFile(String path, boolean validateSignature) throws IOException { File target = downloadFile(path); if (validateSignature) { if (_signers.isEmpty()) { log.info("No signers, not verifying file", "path", path); } else { File signatureFile = downloadFile(path + SIGNATURE_SUFFIX); byte[] signature = null; FileReader reader = null; try { reader = new FileReader(signatureFile); signature = StreamUtil.toByteArray(new FileInputStream(signatureFile)); } finally { StreamUtil.close(reader); signatureFile.delete(); // delete the file regardless } byte[] buffer = new byte[8192]; int length, validated = 0; for (Certificate cert : _signers) { FileInputStream dataInput = null; try { dataInput = new FileInputStream(target); Signature sig = Signature.getInstance("SHA1withRSA"); sig.initVerify(cert); while ((length = dataInput.read(buffer)) != -1) { sig.update(buffer, 0, length); } if (!sig.verify(Base64.decodeBase64(signature))) { log.info("Signature does not match", "cert", cert.getPublicKey()); continue; } else { log.info("Signature matches", "cert", cert.getPublicKey()); validated++; } } catch (IOException ioe) { log.warning("Failure validating signature of " + target + ": " + ioe); } catch (GeneralSecurityException gse) { // no problem! } finally { StreamUtil.close(dataInput); dataInput = null; } } // if we couldn't find a key that validates our digest, we are the hosed! if (validated == 0) { // delete the temporary digest file as we know it is invalid target.delete(); throw new IOException("m.corrupt_digest_signature_error"); } } } // now move the temporary file over the original File original = getLocalPath(path); if (!FileUtil.renameTo(target, original)) { throw new IOException("Failed to rename(" + target + ", " + original + ")"); } }
From source file:org.ejbca.core.protocol.cmp.AuthenticationModulesTest.java
@Test public void test08EECrmfReqMultipleAuthModules() throws NoSuchAlgorithmException, EjbcaException, IOException, Exception { String modules = CmpConfiguration.AUTHMODULE_HMAC + ";" + CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE; String parameters = "foo123" + ";" + "TestCA"; this.cmpConfiguration.setAuthenticationModule(ALIAS, modules); this.cmpConfiguration.setAuthenticationParameters(ALIAS, parameters); this.cmpConfiguration.setRAMode(ALIAS, true); this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration); KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption); PKIMessage msg = genCertReq(issuerDN, USER_DN, keys, this.cacert, this.nonce, this.transid, false, null, null, null, null, pAlg, null); assertNotNull("Generating CrmfRequest failed.", msg); String adminName = "cmpTestAdmin"; KeyPair admkeys = KeyTools.genKeys("1024", "RSA"); AuthenticationToken adminToken = createAdminToken(admkeys, adminName, "CN=" + adminName + ",C=SE", this.caid, SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER); Certificate admCert = getCertFromCredentials(adminToken); CMPCertificate[] extraCert = getCMPCert(admCert); msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, admkeys.getPrivate(), pAlg.getAlgorithm().getId(), "BC"); assertNotNull(msg);/*from w ww .j ava 2s.co m*/ //******************************************** final Signature sig = Signature.getInstance(msg.getHeader().getProtectionAlg().getAlgorithm().getId(), "BC"); sig.initVerify(admCert.getPublicKey()); sig.update(CmpMessageHelper.getProtectedBytes(msg)); boolean verified = sig.verify(msg.getProtection().getBytes()); assertTrue("Signing the message failed.", verified); //******************************************** final ByteArrayOutputStream bao = new ByteArrayOutputStream(); final DEROutputStream out = new DEROutputStream(bao); out.writeObject(msg); final byte[] ba = bao.toByteArray(); // Send request and receive response final byte[] resp = sendCmpHttp(ba, 200, ALIAS); checkCmpResponseGeneral(resp, issuerDN, USER_DN, this.cacert, msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(), true, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()); CertReqMessages ir = (CertReqMessages) msg.getBody().getContent(); Certificate cert2 = checkCmpCertRepMessage(USER_DN, this.cacert, resp, ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue()); assertNotNull("CrmfRequest did not return a certificate", cert2); removeAuthenticationToken(adminToken, admCert, adminName); }
From source file:org.ejbca.core.protocol.cmp.AuthenticationModulesTest.java
@Test public void test12EECrmfNotCheckAdmin() throws NoSuchAlgorithmException, EjbcaException, IOException, Exception { this.cmpConfiguration.setAuthenticationModule(ALIAS, CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE); this.cmpConfiguration.setAuthenticationParameters(ALIAS, "TestCA"); this.cmpConfiguration.setOmitVerificationsInECC(ALIAS, true); this.cmpConfiguration.setRAMode(ALIAS, true); this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration); KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption); PKIMessage msg = genCertReq(issuerDN, USER_DN, keys, this.cacert, this.nonce, this.transid, false, null, null, null, null, pAlg, new DEROctetString(this.nonce)); assertNotNull("Generating CrmfRequest failed.", msg); String adminName = "cmpTestAdmin"; KeyPair admkeys = KeyTools.genKeys("1024", "RSA"); AuthenticationToken adminToken = createAdminToken(admkeys, adminName, "CN=" + adminName + ",C=SE", this.caid, SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER); Certificate admCert = getCertFromCredentials(adminToken); CMPCertificate[] extraCert = getCMPCert(admCert); msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, admkeys.getPrivate(), pAlg.getAlgorithm().getId(), "BC"); assertNotNull(msg);// w w w . ja va 2 s .c o m //******************************************** final Signature sig = Signature.getInstance(msg.getHeader().getProtectionAlg().getAlgorithm().getId(), "BC"); sig.initVerify(admCert.getPublicKey()); sig.update(CmpMessageHelper.getProtectedBytes(msg)); boolean verified = sig.verify(msg.getProtection().getBytes()); assertTrue("Signing the message failed.", verified); //******************************************** final ByteArrayOutputStream bao = new ByteArrayOutputStream(); final DEROutputStream out = new DEROutputStream(bao); out.writeObject(msg); final byte[] ba = bao.toByteArray(); // Send request and receive response final byte[] resp = sendCmpHttp(ba, 200, ALIAS); checkCmpResponseGeneral(resp, issuerDN, USER_DN, this.cacert, msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(), false, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()); ASN1InputStream inputStream = new ASN1InputStream(new ByteArrayInputStream(resp)); try { PKIMessage respObject = PKIMessage.getInstance(inputStream.readObject()); assertNotNull(respObject); PKIBody body = respObject.getBody(); assertEquals(23, body.getType()); ErrorMsgContent err = (ErrorMsgContent) body.getContent(); String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString(); String expectedErrmsg = "Omitting some verifications can only be accepted in RA mode and when the CMP request has already been authenticated, for example, through the use of NestedMessageContent"; assertEquals(expectedErrmsg, errMsg); } finally { inputStream.close(); } removeAuthenticationToken(adminToken, admCert, adminName); }
From source file:com.example.bbbbbb.http.sample.util.SecureSocketFactory.java
/** * Instantiate a new secured factory pertaining to the passed store. Be sure to initialize the * store with the password using {@link KeyStore#load(InputStream, * char[])} method.//from ww w. j a v a2s.c om * * @param store The key store holding the certificate details * @param alias The alias of the certificate to use */ public SecureSocketFactory(KeyStore store, String alias) throws CertificateException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { super(store); // Loading the CA certificate from store. final Certificate rootca = store.getCertificate(alias); // Turn it to X509 format. InputStream is = new ByteArrayInputStream(rootca.getEncoded()); X509Certificate x509ca = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(is); AsyncHttpClient.silentCloseInputStream(is); if (null == x509ca) { throw new CertificateException("Embedded SSL certificate has expired."); } // Check the CA's validity. x509ca.checkValidity(); // Accepted CA is only the one installed in the store. acceptedIssuers = new X509Certificate[] { x509ca }; sslCtx = SSLContext.getInstance("TLS"); sslCtx.init(null, new TrustManager[] { new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { Exception error = null; if (null == chain || 0 == chain.length) { error = new CertificateException("Certificate chain is invalid."); } else if (null == authType || 0 == authType.length()) { error = new CertificateException("Authentication type is invalid."); } else { Log.i(LOG_TAG, "Chain includes " + chain.length + " certificates."); try { for (X509Certificate cert : chain) { Log.i(LOG_TAG, "Server Certificate Details:"); Log.i(LOG_TAG, "---------------------------"); Log.i(LOG_TAG, "IssuerDN: " + cert.getIssuerDN().toString()); Log.i(LOG_TAG, "SubjectDN: " + cert.getSubjectDN().toString()); Log.i(LOG_TAG, "Serial Number: " + cert.getSerialNumber()); Log.i(LOG_TAG, "Version: " + cert.getVersion()); Log.i(LOG_TAG, "Not before: " + cert.getNotBefore().toString()); Log.i(LOG_TAG, "Not after: " + cert.getNotAfter().toString()); Log.i(LOG_TAG, "---------------------------"); // Make sure that it hasn't expired. cert.checkValidity(); // Verify the certificate's public key chain. cert.verify(rootca.getPublicKey()); } } catch (InvalidKeyException e) { error = e; } catch (NoSuchAlgorithmException e) { error = e; } catch (NoSuchProviderException e) { error = e; } catch (SignatureException e) { error = e; } } if (null != error) { Log.e(LOG_TAG, "Certificate error", error); throw new CertificateException(error); } } @Override public X509Certificate[] getAcceptedIssuers() { return acceptedIssuers; } } }, null); setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); }