List of usage examples for java.security.cert Certificate getPublicKey
public abstract PublicKey getPublicKey();
From source file:org.codice.ddf.security.idp.client.SimpleSign.java
public boolean validateSignature(String queryParamsToValidate, String encodedSignature, String encodedPublicKey) throws SignatureException { try {/*from ww w . ja va 2 s .com*/ CertificateFactory certificateFactory = CertificateFactory.getInstance("X509"); Certificate certificate = certificateFactory .generateCertificate(new ByteArrayInputStream(Base64.decodeBase64(encodedPublicKey))); String jceSigAlgo = "SHA1withRSA"; if ("DSA".equalsIgnoreCase(certificate.getPublicKey().getAlgorithm())) { jceSigAlgo = "SHA1withDSA"; } java.security.Signature sig = java.security.Signature.getInstance(jceSigAlgo); sig.initVerify(certificate.getPublicKey()); sig.update(queryParamsToValidate.getBytes("UTF-8")); return sig.verify(Base64.decodeBase64(encodedSignature)); } catch (NoSuchAlgorithmException | InvalidKeyException | CertificateException | UnsupportedEncodingException | java.security.SignatureException e) { throw new SignatureException(e); } }
From source file:org.apache.accumulo.test.util.CertUtils.java
public void createSignedCert(File targetKeystoreFile, String keyName, String keystorePassword, String signerKeystorePath, String signerKeystorePassword) throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException, OperatorCreationException, AccumuloSecurityException, UnrecoverableKeyException, NoSuchProviderException { KeyStore signerKeystore = KeyStore.getInstance(keystoreType); char[] signerPasswordArray = signerKeystorePassword.toCharArray(); try (FileInputStream fis = new FileInputStream(signerKeystorePath)) { signerKeystore.load(fis, signerPasswordArray); }/*from w w w .ja va 2s . c om*/ Certificate signerCert = findCert(signerKeystore); PrivateKey signerKey = findPrivateKey(signerKeystore, signerPasswordArray); KeyPair kp = generateKeyPair(); X509CertificateObject cert = generateCert(keyName, kp, false, signerCert.getPublicKey(), signerKey); char[] password = keystorePassword.toCharArray(); KeyStore keystore = KeyStore.getInstance(keystoreType); keystore.load(null, null); keystore.setCertificateEntry(keyName + "Cert", cert); keystore.setKeyEntry(keyName + "Key", kp.getPrivate(), password, new Certificate[] { cert, signerCert }); try (FileOutputStream fos = new FileOutputStream(targetKeystoreFile)) { keystore.store(fos, password); } }
From source file:org.tolven.security.password.PasswordHolder.java
private void generateSecretKey(File secretKeyFile) { if (getSecretKeyFile().exists()) { throw new RuntimeException("A secretkey file already exists at: " + getSecretKeyFile().getPath()); }//from ww w . java 2 s . c om try { KeyGenerator keyGenerator = KeyGenerator.getInstance("DESede"); keyGenerator.init(112); secretKey = keyGenerator.generateKey(); String alias = getKeyStore().aliases().nextElement(); Certificate adminCert = getKeyStore().getCertificate(alias); PublicKey publicKey = adminCert.getPublicKey(); Cipher cipher = Cipher.getInstance(publicKey.getAlgorithm()); cipher.init(Cipher.WRAP_MODE, publicKey); byte[] encryptedSecretKey = cipher.wrap(secretKey); FileOutputStream out = null; try { out = new FileOutputStream(secretKeyFile); out.write(Base64.encodeBase64(encryptedSecretKey)); } finally { if (out != null) { out.close(); } } } catch (Exception ex) { throw new RuntimeException("Could not generate secret key for file: " + secretKeyFile.getPath(), ex); } }
From source file:org.ejbca.core.model.ca.catoken.BaseCAToken.java
/** * @param keyStore/* w ww. j ava 2 s .c om*/ * @param alias * @return * @throws Exception */ protected PublicKey readPublicKey(KeyStore keyStore, String alias) throws Exception { Certificate cert = keyStore.getCertificate(alias); PublicKey pubk = null; if (cert != null) { pubk = cert.getPublicKey(); } else { log.error(intres.getLocalizedMessage("catoken.nopublic", alias)); if (log.isDebugEnabled()) { Enumeration en = keyStore.aliases(); while (en.hasMoreElements()) { log.debug("Existing alias: " + (String) en.nextElement()); } } } return pubk; }
From source file:org.eclipse.emf.emfstore.client.model.connectionmanager.KeyStoreManager.java
/** * Encrypts a password./* w ww . j a v a 2s .c o m*/ * * @param password * String * @param serverInfo * ServerInfo * @return String */ public String encrypt(String password, ServerInfo serverInfo) { try { Certificate publicKey = getCertificateForEncryption(serverInfo); PublicKey key = publicKey.getPublicKey(); byte[] inpBytes; inpBytes = password.getBytes(); Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] encryptededByteAr = cipher.doFinal(inpBytes); byte[] base64EncodedByteAr = Base64.encodeBase64(encryptededByteAr); return new String(base64EncodedByteAr); // TODO: OW When new login proxy object with encryption handler is // implemented, handle exceptions } catch (NoSuchAlgorithmException e) { // nothing to do e.printStackTrace(); } catch (NoSuchPaddingException e) { // nothing to do e.printStackTrace(); } catch (InvalidKeyException e) { // nothing to do e.printStackTrace(); } catch (IllegalBlockSizeException e) { // nothing to do e.printStackTrace(); } catch (BadPaddingException e) { // nothing to do e.printStackTrace(); } catch (CertificateStoreException e) { // Auto-generated catch block e.printStackTrace(); } WorkspaceUtil.logException("Couldn't encrypt password.", new CertificateStoreException("Couldn't encrypt password.")); return ""; }
From source file:org.eclipse.emf.emfstore.internal.client.model.connectionmanager.KeyStoreManager.java
/** * Encrypts a password./*ww w. j a v a 2 s . c o m*/ * * @param password * the password to be encrypted * @param server * the server from which to fetch the public key that is used for encryption * @return the encrypted password */ public String encrypt(String password, ServerInfo server) { try { final Certificate publicKey = getCertificateForEncryption(server); final PublicKey key = publicKey.getPublicKey(); final byte[] inpBytes = password.getBytes(); final Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, key); final byte[] encryptededByteAr = cipher.doFinal(inpBytes); final byte[] base64EncodedByteAr = Base64.encodeBase64(encryptededByteAr); return new String(base64EncodedByteAr); // TODO: OW When new login proxy object with encryption handler is // implemented, handle exceptions } catch (final NoSuchAlgorithmException e) { // nothing to do e.printStackTrace(); } catch (final NoSuchPaddingException e) { // nothing to do e.printStackTrace(); } catch (final InvalidKeyException e) { // nothing to do e.printStackTrace(); } catch (final IllegalBlockSizeException e) { // nothing to do e.printStackTrace(); } catch (final BadPaddingException e) { // nothing to do e.printStackTrace(); } catch (final ESCertificateException e) { // Auto-generated catch block e.printStackTrace(); } WorkspaceUtil.logException(Messages.KeyStoreManager_Could_Not_Encrypt_Password, new ESCertificateException(Messages.KeyStoreManager_34)); return ""; //$NON-NLS-1$ }
From source file:org.ejbca.ui.cli.ca.CaImportCVCCACommand.java
public void execute(String[] args) throws ErrorAdminCommandException { if (args.length < 4) { getLogger().info("Description: " + getDescription()); getLogger().info(//from ww w . ja v a 2 s. c o m "Usage 1: " + getCommand() + " <CA name> <pkcs8 RSA private key file> <certificate file>"); getLogger().info(" Imports a private key and a self signed CVCA certificate and creates a CVCA."); getLogger().info("Usage 2: " + getCommand() + " <CA name> <pkcs8 private key file> <certificate file> <DN of form C=country,CN=mnemonic,SERIALNUMBER=sequence> <signatureAlgorithm> <validity days>"); getLogger().info( " Imports a private key and generates a new self signed CVCA certificate with the given DN and creates a CVCA."); getLogger().info( " Signature algorithm can be SHA1WithRSA, SHA256WithRSA, SHA1WithECDSA, SHA224WithECDSA, SHA256WithECDSA, etc."); getLogger().info( " SERIALNUMBER will not be a part of the CAs DN, it is only used to set a specified sequence (should be of form 00001). Can be left out, and a random sequence is then generated."); return; } try { String caName = args[1]; String pkFile = args[2]; String certFile = args[3]; // Import key and certificate CryptoProviderTools.installBCProvider(); byte[] pkbytes = FileTools.readFiletoBuffer(pkFile); PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(pkbytes); KeyFactory keyfact = KeyFactory.getInstance("RSA", "BC"); // Doesn't matter if we say RSA here, it will fix an EC key as well PrivateKey privKey = keyfact.generatePrivate(spec); byte[] certbytes = FileTools.readFiletoBuffer(certFile); Certificate cert = null; try { // First check if it was a PEM formatted certificate Collection<Certificate> certs = CertTools.getCertsFromPEM(new ByteArrayInputStream(certbytes)); cert = certs.iterator().next(); } catch (IOException e) { // This was not a PEM certificate, I hope it's binary... cert = CertTools.getCertfromByteArray(certbytes); } PublicKey pubKey = cert.getPublicKey(); // Verify that the public and private key belongs together getLogger().info("Testing keys with algorithm: " + pubKey.getAlgorithm()); KeyTools.testKey(privKey, pubKey, null); Certificate cacert = null; if (args.length > 6) { // Create a self signed CVCA cert from the DN getLogger().info("Generating new self signed certificate."); String dn = args[4]; String sigAlg = args[5]; Integer valdays = Integer.parseInt(args[6]); String country = CertTools.getPartFromDN(dn, "C"); String mnemonic = CertTools.getPartFromDN(dn, "CN"); String seq = CertTools.getPartFromDN(dn, "SERIALNUMBER"); if (StringUtils.isEmpty(seq)) { seq = RandomStringUtils.randomNumeric(5); getLogger().info("No sequence given, using random 5 number sequence: " + seq); } HolderReferenceField holderRef = new HolderReferenceField(country, mnemonic, seq); CAReferenceField caRef = new CAReferenceField(holderRef.getCountry(), holderRef.getMnemonic(), holderRef.getSequence()); AuthorizationRoleEnum authRole = AuthorizationRoleEnum.CVCA; Date notBefore = new Date(); Calendar notAfter = Calendar.getInstance(); notAfter.add(Calendar.DAY_OF_MONTH, valdays); CVCertificate cvc = CertificateGenerator.createCertificate(pubKey, privKey, sigAlg, caRef, holderRef, authRole, AccessRightEnum.READ_ACCESS_DG3_AND_DG4, notBefore, notAfter.getTime(), "BC"); cacert = new CardVerifiableCertificate(cvc); } else { getLogger().info("Using passed in self signed certificate."); cacert = cert; } try { cacert.verify(pubKey); } catch (SignatureException e) { getLogger().info("Can not verify self signed certificate: " + e.getMessage()); System.exit(3); // NOPMD } Certificate[] chain = new Certificate[1]; chain[0] = cacert; ejb.getCAAdminSession().importCAFromKeys(getAdmin(), caName, "foo123", chain, pubKey, privKey, null, null); } catch (ErrorAdminCommandException e) { throw e; } catch (Exception e) { throw new ErrorAdminCommandException(e); } }
From source file:com.microsoft.aad.adal.testapp.MainActivity.java
public void initDeviceCertificateMock() throws NoSuchAlgorithmException, UnrecoverableKeyException, CertificateException, KeyStoreException, IOException { KeyStore keystore = loadTestCertificate(); Key key = keystore.getKey(TEST_CERT_ALIAS, PKCS12_PASS.toCharArray()); RSAPrivateKey privateKey = (RSAPrivateKey) key; Certificate cert = keystore.getCertificate(TEST_CERT_ALIAS); RSAPublicKey publicKey = (RSAPublicKey) cert.getPublicKey(); MockDeviceCertProxy.sValidIssuer = true; MockDeviceCertProxy.sPrivateKey = privateKey; MockDeviceCertProxy.sPublicKey = publicKey; MockDeviceCertProxy.sThumbPrint = "test"; MockDeviceCertProxy.sCertificate = (X509Certificate) cert; AuthenticationSettings.INSTANCE.setDeviceCertificateProxyClass(MockDeviceCertProxy.class); }
From source file:org.forgerock.openidm.security.impl.SecurityResourceProvider.java
/** * Verifies that the supplied private key and signed certificate match by signing/verifying some test data. * //from w w w . j a v a 2 s. c o m * @param privateKey A private key * @param cert the certificate * @throws ResourceException if the verification fails, or an error is encountered. */ protected void verify(PrivateKey privateKey, Certificate cert) throws ResourceException { PublicKey publicKey = cert.getPublicKey(); byte[] data = { 65, 66, 67, 68, 69, 70, 71, 72, 73, 74 }; boolean verified; try { Signature signer = Signature.getInstance(privateKey.getAlgorithm()); signer.initSign(privateKey); signer.update(data); byte[] signed = signer.sign(); Signature verifier = Signature.getInstance(publicKey.getAlgorithm()); verifier.initVerify(publicKey); verifier.update(data); verified = verifier.verify(signed); } catch (Exception e) { throw new InternalServerErrorException("Error verifying private key and signed certificate", e); } if (!verified) { throw new BadRequestException("Private key does not match signed certificate"); } }
From source file:org.apache.cloudstack.network.ssl.CertServiceImpl.java
private void validate(final String certInput, final String keyInput, final String password, final String chainInput) { try {/*from w w w . ja v a 2 s .com*/ List<Certificate> chain = null; final Certificate cert = parseCertificate(certInput); final PrivateKey key = parsePrivateKey(keyInput); if (chainInput != null) { chain = CertificateHelper.parseChain(chainInput); } validateCert(cert); validateKeys(cert.getPublicKey(), key); if (chainInput != null) { validateChain(chain, cert); } } catch (final IOException | CertificateException e) { throw new IllegalStateException("Parsing certificate/key failed: " + e.getMessage(), e); } }