List of usage examples for java.security KeyPair getPrivate
public PrivateKey getPrivate()
From source file:com.atlassian.jira.security.auth.trustedapps.TestDefaultCurrentApplicationStore.java
private void assertState(KeyPair pair, String applicationId, CurrentApplicationStore applicationStore) { assertState(pair.getPublic(), pair.getPrivate(), applicationId, applicationStore); }
From source file:com.vmware.admiral.compute.ConfigureHostOverSshTaskService.java
public void generateServerCertPair(ConfigureHostOverSshTaskServiceState state, AuthCredentialsServiceState credentials, AuthCredentialsServiceState caCert) { KeyPair caKeyPair = CertificateUtil.createKeyPair(caCert.privateKey); X509Certificate caCertificate = CertificateUtil.createCertificate(caCert.publicKey); CertChainKeyPair signedForServer = CertificateUtil.generateSigned(state.address, caCertificate, caKeyPair.getPrivate()); uploadServerPem(state, credentials, signedForServer); }
From source file:io.confluent.rest.SslTest.java
private void createKeystoreWithCert(File file, String alias, Map<String, X509Certificate> certs) throws Exception { KeyPair keypair = TestSslUtils.generateKeyPair("RSA"); // IMPORTANT: CN must be "localhost" because Jetty expects the server CN to be the FQDN. X509Certificate cCert = TestSslUtils.generateCertificate("CN=localhost, O=A client", keypair, 30, "SHA1withRSA"); TestSslUtils.createKeyStore(file.getPath(), new Password(SSL_PASSWORD), alias, keypair.getPrivate(), cCert); certs.put(alias, cCert);/* ww w .jav a2 s . c om*/ }
From source file:org.asimba.wa.integrationtest.saml2.model.Response.java
public String getSignedMessage(SignatureHelper signatureHelper) { if (_responseDocument == null) { try {/*from w w w . j a v a 2 s. c o m*/ _responseDocument = XMLUtils.getDocumentFromString(getResponse(plain), true); } catch (OAException | XMLStreamException e) { _logger.error("Problem when establishing XML document to sign: {}", e.getMessage(), e); return null; } } signatureHelper.tagIdAttributes(_responseDocument); KeyPair keypair = signatureHelper.getKeyPairFromKeystore(); // Set signing context with PrivateKey and root of the Document DOMSignContext dsc = new DOMSignContext(keypair.getPrivate(), _responseDocument.getDocumentElement()); // Get SignatureFactory for creating signatures in DOM: XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM"); Reference ref = null; SignedInfo si = null; XMLSignature signature = null; try { // Create reference for "" -> root of the document // SAML requires enveloped transform List<Transform> transformsList = new ArrayList<>(); transformsList.add(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)); // transformsList.add(fac.newTransform(Transforms.TRANSFORM_C14N_OMIT_COMMENTS, (TransformParameterSpec) null)); ref = fac.newReference("#" + getId(), fac.newDigestMethod(DigestMethod.SHA1, null), transformsList, null, null); // Create SignedInfo (SAML2: Exclusive with or without comments is specified) // .. some selection here; nothing fancy, just trying to switch based on signing key format String sigMethod; String keyAlg = keypair.getPrivate().getAlgorithm(); if (keyAlg.contains("RSA")) { sigMethod = SignatureMethod.RSA_SHA1; } else if (keyAlg.contains("DSA")) { sigMethod = SignatureMethod.DSA_SHA1; } else { _logger.error("Unknown signing key algorithm: {}", keyAlg); return null; } si = fac.newSignedInfo( fac.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null), fac.newSignatureMethod(sigMethod, null), Collections.singletonList(ref)); // Add KeyInfo to the document: KeyInfoFactory kif = fac.getKeyInfoFactory(); // .. get key from the generated keypair: KeyValue kv = kif.newKeyValue(keypair.getPublic()); KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv)); signature = fac.newXMLSignature(si, ki); // Sign! signature.sign(dsc); String s = XMLUtils.getStringFromDocument(_responseDocument); _logger.info("Document after signing whole message:\n{}", s); return s; } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException e) { _logger.error("Could not create reference to signable content: {}", e.getMessage(), e); return null; } catch (KeyException e) { _logger.error("Could not establish key info: {}", e.getMessage(), e); return null; } catch (MarshalException | XMLSignatureException e) { _logger.error("Error signing document: {}", e.getMessage(), e); return null; } catch (OAException e) { _logger.error("Error creating string from XML document: {}", e.getMessage(), e); return null; } }
From source file:com.sshtools.j2ssh.transport.kex.GssGroup1Sha1.java
/** * * * @param clientId// w ww . j av a 2s . c o m * @param serverId * @param clientKexInit * @param serverKexInit * * @throws IOException * @throws AlgorithmOperationException * @throws KeyExchangeException */ public void performClientExchange(String clientId, String serverId, byte[] clientKexInit, byte[] serverKexInit, boolean firstPacketFollows, boolean useFirstPacket, boolean firstExch) throws IOException { try { log.info("Starting client side key exchange."); transport.getMessageStore().registerMessage(SshMsgKexGssInit.SSH_MSG_KEXGSS_INIT, SshMsgKexGssInit.class); transport.getMessageStore().registerMessage(SshMsgKexGssContinue.SSH_MSG_KEXGSS_CONTINUE, SshMsgKexGssContinue.class); transport.getMessageStore().registerMessage(SshMsgKexGssComplete.SSH_MSG_KEXGSS_COMPLETE, SshMsgKexGssComplete.class); transport.getMessageStore().registerMessage(SshMsgKexGssHostKey.SSH_MSG_KEXGSS_HOSTKEY, SshMsgKexGssHostKey.class); transport.getMessageStore().registerMessage(SshMsgKexGssError.SSH_MSG_KEXGSS_ERROR, SshMsgKexGssError.class); this.clientId = clientId; this.serverId = serverId; this.clientKexInit = clientKexInit; this.serverKexInit = serverKexInit; //int minBits = g.bitLength(); //int maxBits = q.bitLength(); //Random rnd = ConfigurationLoader.getRND(); // Generate a random bit count for the random x value /*int genBits = (int) ( ( (maxBits - minBits + 1) * rnd.nextFloat()) + minBits); x = new BigInteger(genBits, rnd); // Calculate e e = g.modPow(x, p);*/ try { DHParameterSpec dhSkipParamSpec = new DHParameterSpec(p, g); dhKeyPairGen.initialize(dhSkipParamSpec); KeyPair dhKeyPair = dhKeyPairGen.generateKeyPair(); dhKeyAgreement.init(dhKeyPair.getPrivate()); x = ((DHPrivateKey) dhKeyPair.getPrivate()).getX(); e = ((DHPublicKey) dhKeyPair.getPublic()).getY(); } catch (InvalidKeyException ex) { throw new AlgorithmOperationException("Failed to generate DH value"); } catch (InvalidAlgorithmParameterException ex) { throw new AlgorithmOperationException("Failed to generate DH value"); } //C calls GSS_Init_sec_context! log.info("Generating shared context with server..."); GlobusGSSManagerImpl globusgssmanagerimpl = new GlobusGSSManagerImpl(); HostAuthorization gssAuth = new HostAuthorization(null); GSSName targetName = gssAuth.getExpectedName(null, hostname); GSSCredential gsscredential = null; GSSContext gsscontext = null; if (theCredential == null) { gsscredential = UserGridCredential.getUserCredential(properties); theCredential = gsscredential; } else { gsscredential = theCredential; try { ((GlobusGSSCredentialImpl) gsscredential).getGlobusCredential().verify(); } catch (NullPointerException e) { e.printStackTrace(); } catch (GlobusCredentialException e) { e.printStackTrace(); javax.swing.JOptionPane.showMessageDialog(properties.getWindow(), "The credentials that you authenticated with have expired, please re-authenticate.", "GSI-SSH Terminal", javax.swing.JOptionPane.WARNING_MESSAGE); gsscredential = UserGridCredential.getUserCredential(properties); theCredential = gsscredential; } } gsscontext = globusgssmanagerimpl.createContext(targetName, GSSConstants.MECH_OID, gsscredential, GSSCredential.DEFAULT_LIFETIME); gsscontext.requestCredDeleg(true); gsscontext.requestMutualAuth(true); gsscontext.requestInteg(true); //gsscontext.requestAnonymity(false); // gsscontext.requestReplayDet(false); //gsscontext.requestSequenceDet(false); // gsscontext.requestConf(false); Object type = GSIConstants.DELEGATION_TYPE_LIMITED; String cur = "None"; if (properties instanceof SshToolsConnectionProfile) { cur = ((SshToolsConnectionProfile) properties) .getApplicationProperty(SshTerminalPanel.PREF_DELEGATION_TYPE, "Full"); if (cur.equals("full")) { type = GSIConstants.DELEGATION_TYPE_FULL; } else if (cur.equals("limited")) { type = GSIConstants.DELEGATION_TYPE_LIMITED; } else if (cur.equals("none")) { type = GSIConstants.DELEGATION_TYPE_LIMITED; gsscontext.requestCredDeleg(false); } } log.debug("Enabling delegation setting: " + cur); ((ExtendedGSSContext) gsscontext).setOption(GSSConstants.DELEGATION_TYPE, type); log.debug("Starting GSS token exchange."); byte abyte2[] = new byte[0]; Object obj = null; boolean firsttime = true; hostKey = null; do { if (gsscontext.isEstablished()) break; byte abyte3[] = gsscontext.initSecContext(abyte2, 0, abyte2.length); if (gsscontext.isEstablished() && !gsscontext.getMutualAuthState()) { // bad authenitcation throw new KeyExchangeException( "Context established without mutual authentication in gss-group1-sha1-* key exchange."); } if (gsscontext.isEstablished() && !gsscontext.getIntegState()) { // bad authenitcation throw new KeyExchangeException( "Context established without integrety protection in gss-group1-sha1-* key exchange."); } if (abyte3 != null) { if (firsttime) { SshMsgKexGssInit msg = new SshMsgKexGssInit(e, /*bytearraywriter1.toByteArray()*/abyte3); transport.sendMessage(msg, this); } else { SshMsgKexGssContinue msg = new SshMsgKexGssContinue( /*bytearraywriter1.toByteArray()*/abyte3); transport.sendMessage(msg, this); } } else { throw new KeyExchangeException("Expecting a non-zero length token from GSS_Init_sec_context."); } if (!gsscontext.isEstablished()) { int[] messageId = new int[3]; messageId[0] = SshMsgKexGssHostKey.SSH_MSG_KEXGSS_HOSTKEY; messageId[1] = SshMsgKexGssContinue.SSH_MSG_KEXGSS_CONTINUE; messageId[2] = SshMsgKexGssError.SSH_MSG_KEXGSS_ERROR; SshMessage msg = transport.readMessage(messageId); if (msg.getMessageId() == SshMsgKexGssHostKey.SSH_MSG_KEXGSS_HOSTKEY) { if (!firsttime) { throw new KeyExchangeException( "Not expecting a SSH_MSG_KEXGS_HOSTKEY message at this time."); } SshMsgKexGssHostKey reply = (SshMsgKexGssHostKey) msg; hostKey = reply.getHostKey(); messageId = new int[2]; messageId[0] = SshMsgKexGssContinue.SSH_MSG_KEXGSS_CONTINUE; messageId[1] = SshMsgKexGssError.SSH_MSG_KEXGSS_ERROR; msg = transport.readMessage(messageId); if (msg.getMessageId() == SshMsgKexGssError.SSH_MSG_KEXGSS_ERROR) errormsg(msg); } else if (msg.getMessageId() == SshMsgKexGssError.SSH_MSG_KEXGSS_ERROR) { errormsg(msg); } SshMsgKexGssContinue reply = (SshMsgKexGssContinue) msg; abyte2 = reply.getToken(); } firsttime = false; } while (true); log.debug("Sending gssapi exchange complete."); int[] messageId = new int[2]; messageId[0] = SshMsgKexGssComplete.SSH_MSG_KEXGSS_COMPLETE; messageId[1] = SshMsgKexGssError.SSH_MSG_KEXGSS_ERROR; SshMessage msg = transport.readMessage(messageId); if (msg.getMessageId() == SshMsgKexGssError.SSH_MSG_KEXGSS_ERROR) errormsg(msg); SshMsgKexGssComplete reply = (SshMsgKexGssComplete) msg; if (reply.hasToken()) { ByteArrayReader bytearrayreader1 = new ByteArrayReader(reply.getToken()); abyte2 = bytearrayreader1.readBinaryString(); byte abyte3[] = gsscontext.initSecContext(abyte2, 0, abyte2.length); if (abyte3 != null) { throw new KeyExchangeException("Expecting zero length token."); } if (gsscontext.isEstablished() && !gsscontext.getMutualAuthState()) { // bad authenitcation throw new KeyExchangeException( "Context established without mutual authentication in gss-group1-sha1-* key exchange."); } if (gsscontext.isEstablished() && !gsscontext.getIntegState()) { // bad authenitcation throw new KeyExchangeException( "Context established without integrety protection in gss-group1-sha1-* key exchange."); } } byte per_msg_token[] = reply.getMIC(); f = reply.getF(); // Calculate diffe hellman k value secret = f.modPow(x, p); // Calculate the exchange hash calculateExchangeHash(); gsscontext.verifyMIC(per_msg_token, 0, per_msg_token.length, exchangeHash, 0, exchangeHash.length, null); gssContext = gsscontext; } catch (GSSException g) { String desc = g.toString(); if (desc.startsWith( "GSSException: Failure unspecified at GSS-API level (Mechanism level: GSS Major Status: Authentication Failed") && desc.indexOf("an unknown error occurred") >= 0) { throw new KeyExchangeException( "Error from GSS layer: \n Probably due to your proxy credential being expired or signed by a CA unknown by the server or your clock being set wrong.", g); } else { if (desc.indexOf("From Server") >= 0) { throw new KeyExchangeException("GSS Error from server", g); } else { throw new KeyExchangeException("Error from GSS layer", g); } } } catch (IOException e) { e.printStackTrace(); throw e; } }
From source file:com.atlassian.jira.security.auth.trustedapps.TestDefaultCurrentApplicationStore.java
private void assertState(final PublicKey publicKey, final PrivateKey privateKey, final String applicationId, final CurrentApplicationStore applicationStore) { CurrentApplication currentApplication = applicationStore.getCurrentApplication(); assertEquals(applicationId, currentApplication.getID()); assertEquals(publicKey, currentApplication.getPublicKey()); KeyPair keyPair = applicationStore.getKeyPair(); assertEquals(publicKey, keyPair.getPublic()); assertEquals(privateKey, keyPair.getPrivate()); // just make sure we have a key final EncryptedCertificate encoded = currentApplication.encode("this little sentence", null); assertNotNull(encoded.getCertificate()); assertEquals(applicationId, encoded.getID()); assertNotNull(encoded.getSecretKey()); }
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); }/*w w w .j a v a2 s . c o m*/ 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:com.trsst.Command.java
public static final void writeKeyPairToFile(KeyPair keyPair, X509Certificate cert, String alias, File file, char[] pwd) { FileInputStream input = null; FileOutputStream output = null; try {// ww w. ja v a2s . com KeyStore keyStore = KeyStore.getInstance("PKCS12"); if (file.exists()) { input = new FileInputStream(file); keyStore.load(new FileInputStream(file), pwd); input.close(); } else { keyStore.load(null); // weird but required } // save my private key keyStore.setKeyEntry(alias, keyPair.getPrivate(), pwd, new X509Certificate[] { cert }); // store away the keystore output = new java.io.FileOutputStream(file); keyStore.store(output, pwd); output.flush(); } catch (Exception e) { log.error("Error while storing key: " + e.getMessage(), e); } finally { if (input != null) { try { input.close(); } catch (IOException e) { // ignore while closing log.trace("Error while closing: " + e.getMessage(), e); } } if (output != null) { try { output.close(); } catch (IOException e) { // ignore while closing log.trace("Error while closing: " + e.getMessage(), e); } } } }
From source file:com.kuzumeji.platform.standard.SecurityService.java
/** * RSA???// www .j a va 2 s . co m * <dl> * <dt>? * <dd>RSA??? * </dl> * @param name RSA??? * @param keyPair RSA? */ public void saveKeyPair(final String name, final KeyPair keyPair) { try { final Properties property = new PropertyService(PROPERTY_NAME).getProperty(); final RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); property.setProperty(String.format(KEY_PUBLIC_ENCODED, name), Hex.encodeHexString(publicKey.getEncoded())); final RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); property.setProperty(String.format(KEY_PRIVATE_ENCODED, name), Hex.encodeHexString(privateKey.getEncoded())); try (FileOutputStream stream = new FileOutputStream( Thread.currentThread().getContextClassLoader().getResource(PROPERTY_NAME).getPath());) { property.store(stream, "RSAPublicKey and RSAPrivateKey"); } } catch (final IOException e) { throw new RuntimeException(e); } }
From source file:org.apache.cloudstack.saml.SAML2AuthManagerImpl.java
protected boolean initSP() { KeystoreVO keyStoreVO = _ksDao.findByName(SAMLPluginConstants.SAMLSP_KEYPAIR); if (keyStoreVO == null) { try {/*from ww w . java 2 s . c o m*/ KeyPair keyPair = SAMLUtils.generateRandomKeyPair(); _ksDao.save(SAMLPluginConstants.SAMLSP_KEYPAIR, SAMLUtils.savePrivateKey(keyPair.getPrivate()), SAMLUtils.savePublicKey(keyPair.getPublic()), "samlsp-keypair"); keyStoreVO = _ksDao.findByName(SAMLPluginConstants.SAMLSP_KEYPAIR); s_logger.info("No SAML keystore found, created and saved a new Service Provider keypair"); } catch (NoSuchProviderException | NoSuchAlgorithmException e) { s_logger.error("Unable to create and save SAML keypair: " + e.toString()); } } String spId = SAMLServiceProviderID.value(); String spSsoUrl = SAMLServiceProviderSingleSignOnURL.value(); String spSloUrl = SAMLServiceProviderSingleLogOutURL.value(); String spOrgName = SAMLServiceProviderOrgName.value(); String spOrgUrl = SAMLServiceProviderOrgUrl.value(); String spContactPersonName = SAMLServiceProviderContactPersonName.value(); String spContactPersonEmail = SAMLServiceProviderContactEmail.value(); KeyPair spKeyPair = null; X509Certificate spX509Key = null; if (keyStoreVO != null) { PrivateKey privateKey = SAMLUtils.loadPrivateKey(keyStoreVO.getCertificate()); PublicKey publicKey = SAMLUtils.loadPublicKey(keyStoreVO.getKey()); if (privateKey != null && publicKey != null) { spKeyPair = new KeyPair(publicKey, privateKey); KeystoreVO x509VO = _ksDao.findByName(SAMLPluginConstants.SAMLSP_X509CERT); if (x509VO == null) { try { spX509Key = SAMLUtils.generateRandomX509Certificate(spKeyPair); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(bos); out.writeObject(spX509Key); out.flush(); _ksDao.save(SAMLPluginConstants.SAMLSP_X509CERT, Base64.encodeBase64String(bos.toByteArray()), "", "samlsp-x509cert"); bos.close(); } catch (NoSuchAlgorithmException | NoSuchProviderException | CertificateEncodingException | SignatureException | InvalidKeyException | IOException e) { s_logger.error("SAML Plugin won't be able to use X509 signed authentication"); } } else { try { ByteArrayInputStream bi = new ByteArrayInputStream( Base64.decodeBase64(x509VO.getCertificate())); ObjectInputStream si = new ObjectInputStream(bi); spX509Key = (X509Certificate) si.readObject(); bi.close(); } catch (IOException | ClassNotFoundException ignored) { s_logger.error( "SAML Plugin won't be able to use X509 signed authentication. Failed to load X509 Certificate from Database."); } } } } if (spKeyPair != null && spX509Key != null && spId != null && spSsoUrl != null && spSloUrl != null && spOrgName != null && spOrgUrl != null && spContactPersonName != null && spContactPersonEmail != null) { _spMetadata.setEntityId(spId); _spMetadata.setOrganizationName(spOrgName); _spMetadata.setOrganizationUrl(spOrgUrl); _spMetadata.setContactPersonName(spContactPersonName); _spMetadata.setContactPersonEmail(spContactPersonEmail); _spMetadata.setSsoUrl(spSsoUrl); _spMetadata.setSloUrl(spSloUrl); _spMetadata.setKeyPair(spKeyPair); _spMetadata.setSigningCertificate(spX509Key); _spMetadata.setEncryptionCertificate(spX509Key); return true; } return false; }