List of usage examples for java.security KeyPair getPrivate
public PrivateKey getPrivate()
From source file:com.vmware.identity.openidconnect.sample.RelyingPartyInstaller.java
private X509Certificate generateCertificate(KeyPair keyPair, String dn) throws Exception { ContentSigner sigGen = new JcaContentSignerBuilder("SHA1withRSA").build(keyPair.getPrivate()); Date startDate = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000); Date endDate = new Date(System.currentTimeMillis() + 365 * 24 * 60 * 60 * 1000); X509v3CertificateBuilder v3CertGen = new JcaX509v3CertificateBuilder(new X500Name("CN=" + dn), new BigInteger(64, new SecureRandom()), startDate, endDate, new X500Name("CN=" + dn), keyPair.getPublic());//from ww w . jav a2 s .c o m X509CertificateHolder certHolder = v3CertGen.build(sigGen); X509Certificate x509Certificate = new JcaX509CertificateConverter().getCertificate(certHolder); return x509Certificate; }
From source file:com.frequencymarketing.citi.saml.UsmSaml.java
private SAMLResponse getSAMLResponse(TyUsmSamlProfileData memberData, String a_clientIp) throws Exception { String memberId = memberData.getMemberId(); SAMLIdentifier idgen = SAMLIdentifierFactory.getInstance(); SAMLResponse samlResponse = new SAMLResponse(); SAMLAssertion samlAssertion = new SAMLAssertion(); SAMLAuthenticationStatement samlAuthenticationStatement = new SAMLAuthenticationStatement(); SAMLSubject samlSubject = new SAMLSubject(new SAMLNameIdentifier(memberId, null, null), Collections.singleton(SAMLSubject.CONF_BEARER), null, null); samlAuthenticationStatement.setSubjectIP(a_clientIp); samlAuthenticationStatement.setSubject(samlSubject); samlAuthenticationStatement.setAuthInstant(new Date()); samlAuthenticationStatement.setAuthMethod(SAMLAuthenticationStatement.AuthenticationMethod_Password); samlAssertion.addStatement(samlAuthenticationStatement); samlAssertion.setId(idgen.getIdentifier()); samlAssertion.setIssuer(getSamlProps().getIssuer()); samlAssertion.setNotBefore(new Date(System.currentTimeMillis() - 30000)); samlAssertion.setNotOnOrAfter(new Date(System.currentTimeMillis() + 90000));//2 minutes samlAssertion.addCondition(new SAMLAudienceRestrictionCondition( Collections.singleton(getSamlProps().getAudienceRestriction()))); //NameIdentifier is the Member id. SAMLAttributeStatement samlsaStatement = new SAMLAttributeStatement(); SAMLSubject l_subject2 = new SAMLSubject(new SAMLNameIdentifier(memberId, null, null), Collections.singleton(SAMLSubject.CONF_BEARER), null, null); samlsaStatement.setSubject(l_subject2); samlsaStatement = addToAttributeStatement(samlsaStatement, "member_id", memberId, null, XML.SAML_NS); samlsaStatement = addToAttributeStatement(samlsaStatement, "agent_id", memberData.getAgentId(), null, XML.SAML_NS);/*from w w w . j a va 2s. c o m*/ samlsaStatement = addToAttributeStatement(samlsaStatement, "mbr_name_first", memberData.getFirstName(), null, XML.SAML_NS); samlsaStatement = addToAttributeStatement(samlsaStatement, "mbr_name_last", memberData.getLastName(), null, XML.SAML_NS); samlsaStatement = addToAttributeStatement(samlsaStatement, "point_balance", memberData.getPointBalance(), null, XML.SAML_NS); samlAssertion.addStatement(samlsaStatement); samlResponse.addAssertion(samlAssertion); samlResponse.setId(idgen.getIdentifier()); //Load the KeyStore KeyStore keystore = CryptoKeystoreUtil.getKeyStore(getSamlProps().getKeystore(), getSamlProps().getKeystorePass().toCharArray()); KeyPair keyPair = CryptoKeystoreUtil.getKeyPair(keystore, getSamlProps().getKeystoreAlias(), getSamlProps().getKeystorePass().toCharArray()); samlResponse.sign(XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1, keyPair.getPrivate(), null); s_logger.debug(samlResponse.toString()); System.out.println(samlResponse); return samlResponse; }
From source file:com.subgraph.vega.internal.http.proxy.ssl.CertificateCreator.java
private void initialize() throws IOException, CertificateException { if (certificateStore.containsCaCertificate()) { caCertificate = certificateStore.getCaCertificate(); caPrivateKey = certificateStore.getCaPrivateKey(); caPublicKey = caCertificate.getPublicKey(); caPemCertificate = createPemCertificate(caCertificate); return;/*from ww w . ja v a 2s. com*/ } final KeyPair caKeyPair = keyGenerator.generateKeyPair(); caPublicKey = caKeyPair.getPublic(); caPrivateKey = caKeyPair.getPrivate(); caCertificate = generateCertificate(caSubject, caKeyPair.getPublic(), caSubject, caPublicKey, caPrivateKey, true); certificateStore.saveCaCertificate(caCertificate, caPrivateKey); caPemCertificate = createPemCertificate(caCertificate); }
From source file:kr.ac.cau.mecs.cass.processor.SignupProcessor.java
@Override public Signal process(Signal signal) { Signal resignal = new Signal(); resignal.setReceiver(signal.getSender()); resignal.setSender("CASS"); resignal.setAction(new Action(Action.ACT_SIGNUP)); if (signal.getPayload() != null && (signal.getPayload().getPayload() instanceof JSONObjectPayload)) { JSONObject jobj = (JSONObject) signal.getPayload().getPayload().getData(); if (jobj.has("userid") && jobj.has("userpw")) { String userid = jobj.optString("userid"); String userpw = jobj.optString("userpw"); //valid payload DBUserEntity _user = UserEntityDAO.getByUserID(session, userid); if (_user != null) { //user exists setGenericMessage(resignal, "user exists"); } else { if (userid.length() > 4) { if (userpw.length() > 4) { //create here _user = new DBUserEntity(); _user.setName(userid); _user.setPassword(userpw); if (_user.getAccessToken() == null) { _user.setAccessToken(new DBAccessTokenEntity()); _user.getAccessToken().setUser(_user); }//from www. j av a 2 s. c o m KeyPair keypair = AccessTokenUtil.generateKeyPair(System.currentTimeMillis()); String usertoken = BCrypt.hashpw(userid, BCrypt.gensalt(12)); String authtoken = AccessTokenUtil.signData(usertoken, keypair.getPrivate()); _user.getAccessToken() .setPrivateKey(AccessTokenUtil.encodePrivateKey(keypair.getPrivate())); _user.getAccessToken() .setPublicKey(AccessTokenUtil.encodePublicKey(keypair.getPublic())); _user.getAccessToken().setAccessToken(authtoken); _user.getAccessToken().setUserToken(usertoken); session.save(_user); session.saveOrUpdate(_user.getAccessToken()); JSONObject jres = new JSONObject(); jres.putOpt("authToken", authtoken); jres.putOpt("userToken", usertoken); resignal.setPayload(new Payload(new JSONObjectPayload(jres))); } else { setGenericMessage(resignal, "pw too short(min 5)"); } } else { setGenericMessage(resignal, "id too short(min 5)"); } } } else { setGenericMessage(resignal, "invalid payload type"); } } else { //inform user invalid payload type setGenericMessage(resignal, "invalid payload type"); } return resignal; }
From source file:org.apache.hadoop.gateway.services.security.impl.BaseKeystoreService.java
/** * Create a self-signed X.509 Certificate * @param dn the X.509 Distinguished Name, eg "CN=Test, L=London, C=GB" * @param pair the KeyPair/* www . j av a2 s. co m*/ * @param days how many days from now the Certificate is valid for * @param algorithm the signing algorithm, eg "SHA1withRSA" */ protected X509Certificate generateCertificate(String dn, KeyPair pair, int days, String algorithm) throws GeneralSecurityException, IOException { PrivateKey privkey = pair.getPrivate(); X509CertInfo info = new X509CertInfo(); Date from = new Date(); Date to = new Date(from.getTime() + days * 86400000l); CertificateValidity interval = new CertificateValidity(from, to); BigInteger sn = new BigInteger(64, new SecureRandom()); X500Name owner = new X500Name(dn); info.set(X509CertInfo.VALIDITY, interval); info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(sn)); info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(owner)); info.set(X509CertInfo.ISSUER, new CertificateIssuerName(owner)); info.set(X509CertInfo.KEY, new CertificateX509Key(pair.getPublic())); info.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3)); AlgorithmId algo = new AlgorithmId(AlgorithmId.md5WithRSAEncryption_oid); info.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(algo)); // Sign the cert to identify the algorithm that's used. X509CertImpl cert = new X509CertImpl(info); cert.sign(privkey, algorithm); // Update the algorith, and resign. algo = (AlgorithmId) cert.get(X509CertImpl.SIG_ALG); info.set(CertificateAlgorithmId.NAME + "." + CertificateAlgorithmId.ALGORITHM, algo); cert = new X509CertImpl(info); cert.sign(privkey, algorithm); return cert; }
From source file:org.apache.usergrid.security.ApigeeSSO2ProviderIT.java
@Test public void testBasicOperation() throws Exception { // create keypair KeyPair kp = RsaProvider.generateKeyPair(1024); PublicKey publicKey = kp.getPublic(); PrivateKey privateKey = kp.getPrivate(); // create provider with private key ApigeeSSO2Provider provider = new MockApigeeSSO2Provider(); provider.setManagement(setup.getMgmtSvc()); provider.setPublicKey(publicKey);//from ww w .j a v a 2 s . c o m // create user, claims and a token for those things User user = createUser(); long exp = System.currentTimeMillis() + 10000; Map<String, Object> claims = createClaims(user.getUsername(), user.getEmail(), exp); String token = Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.RS256, privateKey).compact(); // test that provider can validate the token, get user, return token info TokenInfo tokenInfo = provider.validateAndReturnTokenInfo(token, 86400L); Assert.assertNotNull(tokenInfo); }
From source file:edu.wisc.doit.tcrypt.controller.DownloadController.java
@RequestMapping("/download") public void downloadKey(@RequestParam("serviceName") String serviceName, @RequestParam("keyType") String keyType, HttpServletRequest request, HttpServletResponse response) throws Exception { try {//w w w . ja va 2 s. c o m KeyPair sk = (KeyPair) request.getSession().getAttribute("serviceKey_" + serviceName); response.setContentType("application/x-pem-file"); response.setHeader("Content-Disposition", "attachment; filename=\"" + keyType + "-" + serviceName + ".pem" + "\""); Key key = "private".equalsIgnoreCase(keyType) ? sk.getPrivate() : sk.getPublic(); try (final PEMWriter pemWriter = new PEMWriter(new PrintWriter(response.getOutputStream()))) { pemWriter.writeObject(key); } } catch (Exception e) { logger.error("Issue downloading the key " + keyType, e); throw new Exception(e); } }
From source file:net.padlocksoftware.padlock.validator.ValidatorTest.java
License:asdf
/** * this test actually only works when there is no padlock license key referenced. Disabling the license * check to enforce a 2 week expiry period breaks this test. Thus I am disabling * //from ww w . j ava 2s . co m * @throws Exception */ @Test @Ignore public void testExpired() throws Exception { KeyPair pair = KeyManager.createKeyPair(); License license = LicenseFactory.createLicense(); license.setStartDate(new Date(100)); LicenseSigner signer = LicenseSigner.createLicenseSigner((DSAPrivateKey) pair.getPrivate()); signer.sign(license); String key = new String(Hex.encodeHex(pair.getPublic().getEncoded())); Validator validator = new Validator(license, key); boolean ex = false; try { validator.validate(); } catch (ValidatorException e) { ex = true; } assertTrue(ex); }
From source file:org.apache.usergrid.security.ApigeeSSO2ProviderIT.java
@Test public void testExpiredToken() throws Exception { // create keypair KeyPair kp = RsaProvider.generateKeyPair(1024); PublicKey publicKey = kp.getPublic(); PrivateKey privateKey = kp.getPrivate(); // create provider with private key ApigeeSSO2Provider provider = new MockApigeeSSO2Provider(); provider.setManagement(setup.getMgmtSvc()); provider.setPublicKey(publicKey);/* w ww . j ava 2s. co m*/ // create user, claims and a token for those things User user = createUser(); long exp = System.currentTimeMillis() - 1500; Map<String, Object> claims = createClaims(user.getUsername(), user.getEmail(), exp); String token = Jwts.builder().setClaims(claims).setExpiration(new Date()) .signWith(SignatureAlgorithm.RS256, privateKey).compact(); Thread.sleep(500); // wait for claims to timeout // test that token is expired try { provider.validateAndReturnTokenInfo(token, 86400L); Assert.fail("Should have failed due to expired token"); } catch (BadTokenException e) { Assert.assertTrue(e.getCause() instanceof ExpiredJwtException); } }
From source file:org.apache.usergrid.security.ApigeeSSO2ProviderIT.java
@Test public void testBadSignature() throws Exception { // create old keypair KeyPair kp = RsaProvider.generateKeyPair(1024); PublicKey publicKey = kp.getPublic(); PrivateKey privateKey = kp.getPrivate(); // create new keypair KeyPair kpNew = RsaProvider.generateKeyPair(1024); PrivateKey privateKeyNew = kpNew.getPrivate(); // create mock provider with old public key ApigeeSSO2Provider provider = new MockApigeeSSO2ProviderNewKey(publicKey, publicKey); provider.setManagement(setup.getMgmtSvc()); // create user, claims and a token for those things. Sign with new public key User user = createUser();//from w w w. j a v a 2s .co m long exp = System.currentTimeMillis() + 10000; Map<String, Object> claims = createClaims(user.getUsername(), user.getEmail(), exp); String token = Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.RS256, privateKeyNew).compact(); // test that signature exception thrown try { provider.validateAndReturnTokenInfo(token, 86400L); Assert.fail("Should have failed due to bad signature"); } catch (BadTokenException e) { Assert.assertTrue(e.getCause() instanceof SignatureException); } }