List of usage examples for java.security KeyPair getPublic
public PublicKey getPublic()
From source file:com.wandrell.util.ksgen.BouncyCastleKeyStoreFactory.java
/** * Returns a {@code Certificate} with the received data. * * @param keypair//www . j a va 2 s . co m * key pair for the certificate * @param issuer * issuer for the certificate * @return a {@code Certificate} with the received data * @throws IOException * if there is an I/O or format problem with the certificate * data * @throws OperatorCreationException * if there was a problem creation a bouncy castle operator * @throws CertificateException * if any of the certificates in the keystore could not be * loaded * @throws InvalidKeyException * if there was a problem with the key * @throws NoSuchAlgorithmException * if an algorithm required to create the key store could not be * found * @throws NoSuchProviderException * if a required provider is missing * @throws SignatureException * if any problem occurs while signing the certificate */ private final Certificate getCertificate(final KeyPair keypair, final String issuer) throws IOException, OperatorCreationException, CertificateException, InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException, SignatureException { final X509v3CertificateBuilder builder; // Certificate builder final X509Certificate certificate; // Certificate // Generates the certificate builder builder = getCertificateBuilder(keypair.getPublic(), issuer); // Generates the signed certificate certificate = getSignedCertificate(builder, keypair.getPrivate()); // Verifies the certificate certificate.checkValidity(getCurrentDate()); certificate.verify(keypair.getPublic()); LOGGER.debug("Created certificate of type {} with encoded value {}", certificate.getType(), Arrays.asList(certificate.getEncoded())); LOGGER.debug("Created certificate with public key:{}", certificate.getPublicKey()); return certificate; }
From source file:com.thoughtworks.go.security.X509CertificateGenerator.java
public Registration createAgentCertificate(final File authorityKeystore, String agentHostname) { Date epoch = new Date(0); KeyPair agentKeyPair = generateKeyPair(); try {//from w w w . java2 s .com KeyStore store = loadOrCreateCAKeyStore(authorityKeystore); KeyStore.PrivateKeyEntry intermediateEntry = (KeyStore.PrivateKeyEntry) store .getEntry("ca-intermediate", new KeyStore.PasswordProtection(PASSWORD_AS_CHAR_ARRAY)); X509Certificate[] chain = new X509Certificate[3]; chain[2] = (X509Certificate) store.getCertificate("ca-cert"); chain[1] = (X509Certificate) intermediateEntry.getCertificate(); chain[0] = createAgentCertificate(agentKeyPair.getPublic(), intermediateEntry.getPrivateKey(), chain[1].getPublicKey(), agentHostname, epoch); return new Registration(agentKeyPair.getPrivate(), chain); } catch (Exception e) { throw bomb("Couldn't create agent certificate", e); } }
From source file:org.apache.openaz.xacml.pdp.test.custom.TestCustom.java
/** * This function generates the public/private key pair. Should never have to call this again, this was * called once to generate the keys. They were saved into the testsets/custom/datatype-function * sub-directory.//from w w w. j a va2 s .c o m */ public void generateKeyPair() { // // Generate a RSA private/public key pair // KeyPairGenerator keyGen; try { keyGen = KeyPairGenerator.getInstance(ALGORITHM); } catch (NoSuchAlgorithmException e) { logger.error("failed to generate keypair: " + e); return; } keyGen.initialize(1024); final KeyPair key = keyGen.generateKeyPair(); // // Save the keys to disk // Path file = Paths.get(this.directory, PRIVATEKEY_FILE); try (ObjectOutputStream os = new ObjectOutputStream(Files.newOutputStream(file))) { os.writeObject(key.getPrivate()); } catch (IOException e) { e.printStackTrace(); } file = Paths.get(this.directory, PUBLICKEY_FILE); try (ObjectOutputStream os = new ObjectOutputStream(Files.newOutputStream(file))) { os.writeObject(key.getPublic()); } catch (IOException e) { e.printStackTrace(); } }
From source file:net.maritimecloud.identityregistry.controllers.BaseControllerWithCertificate.java
protected PemCertificate issueCertificate(CertificateModel certOwner, Organization org, String type, HttpServletRequest request) throws McBasicRestException { // Generate keypair for user KeyPair userKeyPair = CertificateUtil.generateKeyPair(); // Find special MC attributes to put in the certificate HashMap<String, String> attrs = getAttr(certOwner); String o = org.getMrn();/*from ww w . ja va2s . com*/ String name = getName(certOwner); String email = getEmail(certOwner); String uid = getUid(certOwner); if (uid == null || uid.trim().isEmpty()) { throw new McBasicRestException(HttpStatus.BAD_REQUEST, MCIdRegConstants.ENTITY_ORG_ID_MISSING, request.getServletPath()); } BigInteger serialNumber = certUtil.generateSerialNumber(); X509Certificate userCert = certUtil.generateCertForEntity(serialNumber, org.getCountry(), o, type, name, email, uid, userKeyPair.getPublic(), attrs); String pemCertificate; try { pemCertificate = CertificateUtil.getPemFromEncoded("CERTIFICATE", userCert.getEncoded()).replace("\n", "\\n"); } catch (CertificateEncodingException e) { throw new RuntimeException(e.getMessage(), e); } String pemPublicKey = CertificateUtil.getPemFromEncoded("PUBLIC KEY", userKeyPair.getPublic().getEncoded()) .replace("\n", "\\n"); String pemPrivateKey = CertificateUtil .getPemFromEncoded("PRIVATE KEY", userKeyPair.getPrivate().getEncoded()).replace("\n", "\\n"); PemCertificate ret = new PemCertificate(pemPrivateKey, pemPublicKey, pemCertificate); // Create the certificate Certificate newMCCert = new Certificate(); certOwner.assignToCert(newMCCert); newMCCert.setCertificate(pemCertificate); newMCCert.setSerialNumber(serialNumber); // The dates we extract from the cert is in localtime, so they are converted to UTC before saving into the DB Calendar cal = Calendar.getInstance(); long offset = cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET); newMCCert.setStart(new Date(userCert.getNotBefore().getTime() - offset)); newMCCert.setEnd(new Date(userCert.getNotAfter().getTime() - offset)); this.certificateService.saveCertificate(newMCCert); return ret; }
From source file:org.cesecore.authentication.SimpleAuthenticationProviderSessionBean.java
/** * This is the pug of authentication; loves everybody. *//* www.java 2 s.c om*/ @Override public AuthenticationToken authenticate(AuthenticationSubject subject) { // A small check if we have added a "fail" credential to the subject. // If we have we will return null, so we can test authentication failure. Set<?> usercredentials = subject.getCredentials(); if ((usercredentials != null) && (usercredentials.size() > 0)) { Object o = usercredentials.iterator().next(); if (o instanceof String) { String str = (String) o; if (StringUtils.equals("fail", str)) { return null; } } } X509Certificate certificate = null; // If we have a certificate as input, use that, otherwise generate a self signed certificate Set<X509Certificate> credentials = new HashSet<X509Certificate>(); Set<?> inputcreds = subject.getCredentials(); if (inputcreds != null) { for (Object object : inputcreds) { if (object instanceof X509Certificate) { certificate = (X509Certificate) object; } } } // If there was no certificate input, create a self signed if (certificate == null) { String dn = "C=SE,O=Test,CN=Test"; // default // If we have created a subject with an X500Principal we will use this DN to create the dummy certificate. if (subject != null) { Set<Principal> principals = subject.getPrincipals(); if ((principals != null) && (principals.size() > 0)) { Principal p = principals.iterator().next(); if (p instanceof X500Principal) { X500Principal xp = (X500Principal) p; dn = xp.getName(); } } } KeyPair keys = null; try { keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); } catch (NoSuchAlgorithmException e) { throw new InvalidAuthenticationTokenException("Could not create authentication token.", e); } catch (NoSuchProviderException e) { throw new InvalidAuthenticationTokenException("Could not create authentication token.", e); } catch (InvalidAlgorithmParameterException e) { throw new InvalidAuthenticationTokenException("Could not create authentication token.", e); } try { certificate = CertTools.genSelfCert(dn, 365, null, keys.getPrivate(), keys.getPublic(), AlgorithmConstants.SIGALG_SHA1_WITH_RSA, true); } catch (InvalidKeyException e) { throw new CertificateCreationException("Error encountered when creating certificate", e); } catch (CertificateEncodingException e) { throw new CertificateCreationException("Error encountered when creating certificate", e); } catch (NoSuchAlgorithmException e) { throw new CertificateCreationException("Error encountered when creating certificate", e); } catch (SignatureException e) { throw new CertificateCreationException("Error encountered when creating certificate", e); } catch (IllegalStateException e) { throw new CertificateCreationException("Error encountered when creating certificate", e); } catch (NoSuchProviderException e) { throw new CertificateCreationException("Error encountered when creating certificate", e); } } // Add the credentials and new principal credentials.add(certificate); Set<X500Principal> principals = new HashSet<X500Principal>(); principals.add(certificate.getSubjectX500Principal()); // We cannot use the X509CertificateAuthenticationToken here, since it can only be used internally in a JVM. AuthenticationToken result = new TestAuthenticationToken(principals, credentials); return result; }
From source file:org.apache.xml.security.test.encryption.XMLCipherTester.java
/** * Test encryption using a generated AES 256 bit key that is * encrypted using an RSA key. Reverse using KEK *//* ww w . ja va 2 s . c o m*/ public void testAES128ElementRSAKWCipherUsingKEK() throws Exception { Document d = document(); // source Document ed = null; Document dd = null; Element e = (Element) d.getElementsByTagName(element()).item(index()); Element ee = null; String source = null; String target = null; if (haveISOPadding) { source = toString(d); // Generate an RSA key KeyPairGenerator rsaKeygen = KeyPairGenerator.getInstance("RSA"); KeyPair kp = rsaKeygen.generateKeyPair(); PrivateKey priv = kp.getPrivate(); PublicKey pub = kp.getPublic(); // Generate a traffic key KeyGenerator keygen = KeyGenerator.getInstance("AES"); keygen.init(256); Key key = keygen.generateKey(); cipher = XMLCipher.getInstance(XMLCipher.RSA_v1dot5); cipher.init(XMLCipher.WRAP_MODE, pub); EncryptedKey encryptedKey = cipher.encryptKey(d, key); // encrypt cipher = XMLCipher.getInstance(XMLCipher.AES_256); cipher.init(XMLCipher.ENCRYPT_MODE, key); EncryptedData builder = cipher.getEncryptedData(); KeyInfo builderKeyInfo = builder.getKeyInfo(); if (builderKeyInfo == null) { builderKeyInfo = new KeyInfo(d); builder.setKeyInfo(builderKeyInfo); } builderKeyInfo.add(encryptedKey); ed = cipher.doFinal(d, e); log.debug("Encrypted document"); log.debug(toString(ed)); //decrypt key = null; ee = (Element) ed.getElementsByTagName("xenc:EncryptedData").item(0); cipher = XMLCipher.getInstance(XMLCipher.AES_128); cipher.init(XMLCipher.DECRYPT_MODE, null); cipher.setKEK(priv); dd = cipher.doFinal(ed, ee); target = toString(dd); log.debug("Output document"); log.debug(target); Assert.assertEquals(source, target); } else { log.warn("Test testAES128ElementRSAKWCipherUsingKEK skipped as necessary algorithms not available"); } }
From source file:org.apache.hadoop.yarn.server.resourcemanager.security.X509SecurityHandler.java
private PKCS10CertificationRequest createCSR(X500Name subject, KeyPair keyPair) throws OperatorCreationException { PKCS10CertificationRequestBuilder csrBuilder = new JcaPKCS10CertificationRequestBuilder(subject, keyPair.getPublic()); return csrBuilder.build(new JcaContentSignerBuilder(SIGNATURE_ALGORITHM).setProvider(SECURITY_PROVIDER) .build(keyPair.getPrivate())); }
From source file:test.integ.be.agiv.security.IPSTSTest.java
private X509Certificate generateSelfSignedCertificate(KeyPair keyPair, String subjectDn, DateTime notBefore, DateTime notAfter) throws IOException, InvalidKeyException, IllegalStateException, NoSuchAlgorithmException, SignatureException, CertificateException { PublicKey subjectPublicKey = keyPair.getPublic(); PrivateKey issuerPrivateKey = keyPair.getPrivate(); String signatureAlgorithm = "SHA1WithRSAEncryption"; X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator(); certificateGenerator.reset();/*from w w w . j av a 2 s .c o m*/ certificateGenerator.setPublicKey(subjectPublicKey); certificateGenerator.setSignatureAlgorithm(signatureAlgorithm); certificateGenerator.setNotBefore(notBefore.toDate()); certificateGenerator.setNotAfter(notAfter.toDate()); X509Principal issuerDN = new X509Principal(subjectDn); certificateGenerator.setIssuerDN(issuerDN); certificateGenerator.setSubjectDN(new X509Principal(subjectDn)); certificateGenerator.setSerialNumber(new BigInteger(128, new SecureRandom())); certificateGenerator.addExtension(X509Extensions.SubjectKeyIdentifier, false, createSubjectKeyId(subjectPublicKey)); PublicKey issuerPublicKey; issuerPublicKey = subjectPublicKey; certificateGenerator.addExtension(X509Extensions.AuthorityKeyIdentifier, false, createAuthorityKeyId(issuerPublicKey)); certificateGenerator.addExtension(X509Extensions.BasicConstraints, false, new BasicConstraints(true)); X509Certificate certificate; certificate = certificateGenerator.generate(issuerPrivateKey); /* * Next certificate factory trick is needed to make sure that the * certificate delivered to the caller is provided by the default * security provider instead of BouncyCastle. If we don't do this trick * we might run into trouble when trying to use the CertPath validator. */ CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); certificate = (X509Certificate) certificateFactory .generateCertificate(new ByteArrayInputStream(certificate.getEncoded())); return certificate; }
From source file:org.apache.hadoop.yarn.server.resourcemanager.security.TestHopsworksRMAppSecurityActions.java
private PKCS10CertificationRequest generateCSR(String cn) throws Exception { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC"); keyPairGenerator.initialize(1024);//from w w w.jav a 2 s .co m KeyPair keyPair = keyPairGenerator.genKeyPair(); X500NameBuilder x500NameBuilder = new X500NameBuilder(BCStyle.INSTANCE); x500NameBuilder.addRDN(BCStyle.CN, cn); x500NameBuilder.addRDN(BCStyle.O, O); x500NameBuilder.addRDN(BCStyle.OU, OU); X500Name x500Name = x500NameBuilder.build(); PKCS10CertificationRequestBuilder csrBuilder = new JcaPKCS10CertificationRequestBuilder(x500Name, keyPair.getPublic()); return csrBuilder .build(new JcaContentSignerBuilder("SHA256withRSA").setProvider("BC").build(keyPair.getPrivate())); }
From source file:edu.wisc.doit.tcrypt.dao.impl.KeysKeeper.java
@Override public KeyPair createServiceKey(String serviceName, int keyLength, String username) throws IOException { if (this.keysCache.containsKey(serviceName)) { throw new IllegalArgumentException("'" + serviceName + "' service key already exists."); }/*w w w .j a v a 2 s. c om*/ logger.debug("Generating {} bit KeyPair for service {} requested by {}", keyLength, serviceName, username); final KeyPair keyPair = this.keyPairGenerator.generateKeyPair(keyLength); // Build File Name // Pattern: SERVICENAME_NETID_YYYYMMDDHHMMSS_KEYLENGTH_public.pem final String fileName = serviceName + "_" + username + "_" + KEY_CREATED_FORMATTER.print(DateTime.now()) + "_" + keyLength + "_public.pem"; final File publicKeyFile = new File(this.directory, fileName); if (publicKeyFile.exists()) { logger.warn("Key file already exists at {} it will be overwritten.", publicKeyFile); publicKeyFile.delete(); } try (final PEMWriter pemWriter = new PEMWriter(new BufferedWriter(new FileWriter(publicKeyFile)))) { pemWriter.writeObject(keyPair.getPublic()); } logger.info("Wrote new public key for {} to {}", serviceName, publicKeyFile); this.forcedScanForKeys(); return keyPair; }