List of usage examples for java.security Signature initVerify
public final void initVerify(Certificate certificate) throws InvalidKeyException
From source file:org.loklak.api.cms.LoginService.java
@Override public JSONObject serviceImpl(Query post, HttpServletResponse response, Authorization authorization, final JSONObjectWithDefault permissions) throws APIException { // login check for app if (post.get("checkLogin", false)) { JSONObject result = new JSONObject(); if (authorization.getIdentity().isEmail()) { result.put("loggedIn", true); result.put("message", "You are logged in as " + authorization.getIdentity().getName()); } else {//from w ww .ja v a2s . co m result.put("loggedIn", false); result.put("message", "Not logged in"); } return result; } // do logout if requested if (post.get("logout", false)) { // logout if requested // invalidate session post.getRequest().getSession().invalidate(); // delete cookie if set deleteLoginCookie(response); JSONObject result = new JSONObject(); result.put("message", "Logout successful"); return result; } // check login type by checking which parameters are set boolean passwordLogin = false; boolean pubkeyHello = false; boolean pubkeyLogin = false; if (post.get("login", null) != null && post.get("password", null) != null && post.get("type", null) != null) { passwordLogin = true; } else if (post.get("login", null) != null && post.get("keyhash", null) != null) { pubkeyHello = true; } else if (post.get("sessionID", null) != null && post.get("response", null) != null) { pubkeyLogin = true; } else { throw new APIException(400, "Bad login parameters."); } // check if user is blocked because of too many invalid login attempts checkInvalidLogins(post, authorization, permissions); if (passwordLogin) { // do login via password String login = post.get("login", null); String password = post.get("password", null); String type = post.get("type", null); Authentication authentication = getAuthentication(post, authorization, new ClientCredential(ClientCredential.Type.passwd_login, login)); ClientIdentity identity = authentication.getIdentity(); // check if the password is valid String passwordHash; String salt; try { passwordHash = authentication.getString("passwordHash"); salt = authentication.getString("salt"); } catch (Throwable e) { Log.getLog().info("Invalid login try for user: " + identity.getName() + " from host: " + post.getClientHost() + " : password or salt missing in database"); throw new APIException(422, "Invalid credentials"); } if (!passwordHash.equals(getHash(password, salt))) { // save invalid login in accounting object authorization.getAccounting().addRequest(this.getClass().getCanonicalName(), "invalid login"); Log.getLog().info("Invalid login try for user: " + identity.getName() + " via passwd from host: " + post.getClientHost()); throw new APIException(422, "Invalid credentials"); } JSONObject result = new JSONObject(); switch (type) { case "session": // create a browser session post.getRequest().getSession().setAttribute("identity", identity); break; case "cookie": // set a long living cookie // create random string as token String loginToken = createRandomString(30); // create cookie Cookie loginCookie = new Cookie("login", loginToken); loginCookie.setPath("/"); loginCookie.setMaxAge(defaultCookieTime.intValue()); // write cookie to database ClientCredential cookieCredential = new ClientCredential(ClientCredential.Type.cookie, loginToken); JSONObject user_obj = new JSONObject(); user_obj.put("id", identity.toString()); user_obj.put("expires_on", Instant.now().getEpochSecond() + defaultCookieTime); DAO.authentication.put(cookieCredential.toString(), user_obj, cookieCredential.isPersistent()); response.addCookie(loginCookie); break; case "access-token": // create and display an access token long valid_seconds; try { valid_seconds = post.get("valid_seconds", defaultAccessTokenExpireTime); } catch (Throwable e) { throw new APIException(400, "Invalid value for 'valid_seconds'"); } String token = createAccessToken(identity, valid_seconds); if (valid_seconds == -1) result.put("valid_seconds", "forever"); else result.put("valid_seconds", valid_seconds); result.put("access_token", token); break; default: throw new APIException(400, "Invalid type"); } Log.getLog().info( "login for user: " + identity.getName() + " via passwd from host: " + post.getClientHost()); result.put("message", "You are logged in as " + identity.getName()); return result; } else if (pubkeyHello) { // first part of pubkey login: if the key hash is known, create a challenge String login = post.get("login", null); String keyHash = post.get("keyhash", null); Authentication authentication = getAuthentication(post, authorization, new ClientCredential(ClientCredential.Type.passwd_login, login)); ClientIdentity identity = authentication.getIdentity(); if (!DAO.login_keys.has(identity.toString()) || !DAO.login_keys.getJSONObject(identity.toString()).has(keyHash)) throw new APIException(400, "Unknown key"); String challengeString = createRandomString(30); String newSessionID = createRandomString(30); ClientCredential credential = new ClientCredential(ClientCredential.Type.pubkey_challange, newSessionID); Authentication challenge_auth = new Authentication(credential, DAO.authentication); challenge_auth.setIdentity(identity); challenge_auth.put("activated", true); challenge_auth.put("challenge", challengeString); challenge_auth.put("key", DAO.login_keys.getJSONObject(identity.toString()).getString(keyHash)); challenge_auth.setExpireTime(60 * 10); JSONObject result = new JSONObject(); result.put("challenge", challengeString); result.put("sessionID", newSessionID); result.put("message", "Found valid key for this user. Sign the challenge with you public key and send it back, together with the sessionID"); return result; } else if (pubkeyLogin) { // second part of pubkey login: verify if the response to the challange is valid String sessionID = post.get("sessionID", null); String challangeResponse = post.get("response", null); Authentication authentication = getAuthentication(post, authorization, new ClientCredential(ClientCredential.Type.pubkey_challange, sessionID)); ClientIdentity identity = authentication.getIdentity(); String challenge = authentication.getString("challenge"); PublicKey key = IO.decodePublicKey(authentication.getString("key"), "RSA"); Signature sig; boolean verified; try { sig = Signature.getInstance("SHA256withRSA"); sig.initVerify(key); sig.update(challenge.getBytes()); verified = sig.verify(Base64.getDecoder().decode(challangeResponse)); } catch (NoSuchAlgorithmException e) { throw new APIException(400, "No such algorithm"); } catch (InvalidKeyException e) { throw new APIException(400, "Invalid key"); } catch (Throwable e) { throw new APIException(400, "Bad signature"); } if (verified) { long valid_seconds; try { valid_seconds = post.get("valid_seconds", defaultAccessTokenExpireTime); } catch (Throwable e) { throw new APIException(400, "Invalid value for 'valid_seconds'"); } String token = createAccessToken(identity, valid_seconds); JSONObject result = new JSONObject(); if (valid_seconds == -1) result.put("valid_seconds", "forever"); else result.put("valid_seconds", valid_seconds); result.put("access_token", token); return result; } else { authorization.getAccounting().addRequest(this.getClass().getCanonicalName(), "invalid login"); throw new APIException(400, "Bad Signature"); } } throw new APIException(500, "Server error"); }
From source file:com.vmware.identity.samlservice.SamlServiceTest.java
@Test public void testVerifySignatureVcd2() throws Exception { // pick a sample VCD message String message = "SAMLResponse=fZJNb%2BIwEIb%2FSuR7%2FJWQJhYBrRatVK" + "lcCsuhl5XjTCAosbMZm%2B7P3wClHxx6nPE7M%2B884%2FnyX99FJxixdb" + "YkgnISgTWubu2%2BJL%2B3v%2BKcLBdz1H0nB%2FXk9i74Z8DBWYRoKrWo" + "rm8lCaNVTmOLyuoeUHmjNj%2FWT0pSrobReWdcR6IVoG%2Bt9pdxB%2B8H" + "VIyJQlKR5VTIggqu8jRNmOlcqNm5OdtMZjq4Dme6azWyk6lJ9LgqyZ%2Bq" + "SUzKCw41AM%2BNEEZC1dQJT7K0qJJmktmb460riZamqhueFW1xNKI6pqbh" + "TXtIjqbJk6Sa5IgBHi16bX1JJBcy5lkssy3nSsyUEFTM8hcS7W7QpgXJGy" + "J1KR4%2Fk%2FkejEaE8QyDLG4whrE%2FxLbtq4DxqY%2FFwywWklOwe3rq" + "X%2FUI1LhePaRpyl6hQnTs3E2yNXhda6%2BZwWHOPtt5v9%2FGax%2FwLv" + "zpaoh2ugvwvVW8qNUmGAOIhN21WU9JvYfFM%2FwN040jvOqa0L2ZuRfepT" + "%2Fir79s8R8%3D&SigAlg=http%3A%2F%2Fwww.w3.org%2F2001%2F04%" + "2Fxmldsig-more%23rsa-sha256"; // sign using our algorithm SignatureAlgorithm algo = SignatureAlgorithm.getSignatureAlgorithmForURI(TestConstants.SIGNATURE_ALGORITHM); Signature sig = Signature.getInstance(algo.getAlgorithmName()); sig.initSign(privateKey);//from ww w . j a v a 2s .c om byte[] messageBytes = message.getBytes(); sig.update(messageBytes); byte[] sigBytes = sig.sign(); String signature = Shared.encodeBytes(sigBytes); // verify signature here sig.initVerify(x509Certificate.getPublicKey()); sig.update(messageBytes); boolean verifies = sig.verify(sigBytes); log.debug("signature verifies in test: " + verifies); // just call verifySignature method and expect to not throw service.verifySignature(message, signature); /* disabled now: task 1301740 // import our csp settings CasIdmClient idmClient = new CasIdmClient(SharedUtils.getIdmHostName()); SharedUtils.importConfiguration(idmClient, VSPHERE_LOCAL_TENANT, "/csp2.xml"); CasIdmAccessor idmAccessor = new CasIdmAccessor(idmClient); log.debug("CSP settings imported successfully"); idmAccessor.setTenant(VSPHERE_LOCAL_TENANT); // create new SamlService SamlServiceFactory factory2 = new DefaultSamlServiceFactory(); CertificateFactory certFactory = CertificateFactory .getInstance("X.509"); CertPath certPath = certFactory.generateCertPath(idmAccessor .getSAMLAuthorityChain()); SamlService service2 = factory2.createSamlService( idmClient.getTenantPrivateKey(VSPHERE_LOCAL_TENANT), SignatureAlgorithm.RSA_SHA256, SignatureAlgorithm.RSA_SHA256, idmClient.getEntityID(VSPHERE_LOCAL_TENANT), certPath); // now call it again with generated signature String vcdSignature = "tTUaPscQSmPKkqP9XGgCHZYoH%2FUy2MvZ1eoeP%2B3Y" + "nTDLxiuV5glxngtMbOGspo9NbL37lNVjdCUo7qQVDznUNmKpIOGa%2BGwE" + "jcgqeS7mBDsYPcICxVHZPYxbIaFCmlTIo125olswe4LuP92lIroe%2B%2F" + "DpeNXIGjUAFLHQwlLO7r73cHLH%2BPY2pcYww4X2I7Mhk%2FQ7I3tdMX1O" + "eOhqcRpMn8uyOs6JmVbMoVXuTVKyO96LmQUPCQVLmVjDeD%2BZjVALVLbs" + "vjWsdFt%2F%2Ff2MEXIQkYmeIM5HxZ5rW0uXRocarUrp8nhgxk%2FEQGhk" + "00KYP1xZTCC9JZR6OcbXJZZemBgq%2BA%3D%3D"; vcdSignature = URLDecoder.decode(vcdSignature, "UTF-8"); // just call verifySignature method and expect to not throw service2.verifySignature(message, vcdSignature); */ }
From source file:com.vmware.identity.samlservice.SamlServiceTest.java
@Test public void testVerifySignatureVcd() throws Exception { // pick a sample VCD message String message = "SAMLResponse=fZJNb9swDIb%2FiqF7LPnbEeIUw4oCAVoMqN" + "MedhlomU49yJJrSml%2F%2FuykX8uhFwGkXpKvHmpz9Tro4IgT9dZULAoF" + "C9Ao2%2FbmULGH%2Fc2qZFfbDcGg41He2oP17h5ptIYwmEsNyfNdxfxkpA" + "XqSRoYkKRTsv5xdyvjUMhxss4qq1lwjeR6A%2B407sm5kSTnkQijtAgzES" + "apTNOEK219y%2B104IpGvkzg9exI49kBB90D8aNqWbC7rtifrmkhVaop26h" + "oijJLEOajXBdtl2KSZ7PMvNve24pBmkG%2BLiBumr%2BJyNZJLqKuzRC7J" + "4RmZrAj8rgz5MC4isUiilciW8XRPo5klktRhlGZ%2FmbB4zu5%2BZXsjZM" + "8FU9f8XxPB4hwWoiw7UJkBqJ7419XAGMeNqg1Hj2Gx%2BEFJgyVHWQhSsF" + "fsCGyfOkS87r%2BtaDa8K8OPvZWO3CeLsKftsXgEbTH793RSS1rrxQSMX7" + "R5m5OwgG39%2Fjs590GdNZ1Xr%2BZuRRepD%2Fj%2F3%2FX9h8%3D&SigA" + "lg=http%3A%2F%2Fwww.w3.org%2F2001%2F04%2Fxmldsig-more%23rs" + "a-sha256"; // sign using our algorithm SignatureAlgorithm algo = SignatureAlgorithm.getSignatureAlgorithmForURI(TestConstants.SIGNATURE_ALGORITHM); Signature sig = Signature.getInstance(algo.getAlgorithmName()); sig.initSign(privateKey);//www. j a va 2 s .c o m byte[] messageBytes = message.getBytes(); sig.update(messageBytes); byte[] sigBytes = sig.sign(); String signature = Shared.encodeBytes(sigBytes); // verify signature here sig.initVerify(x509Certificate.getPublicKey()); sig.update(messageBytes); boolean verifies = sig.verify(sigBytes); log.debug("signature verifies in test: " + verifies); // just call verifySignature method and expect to not throw service.verifySignature(message, signature); /* disabled now: task 1301740 // import our csp settings CasIdmClient idmClient = new CasIdmClient(SharedUtils.getIdmHostName()); SharedUtils.importConfiguration(idmClient, VSPHERE_LOCAL_TENANT, "/csp.xml"); CasIdmAccessor idmAccessor = new CasIdmAccessor(idmClient); log.debug("CSP settings imported successfully"); idmAccessor.setTenant(VSPHERE_LOCAL_TENANT); // create new SamlService SamlServiceFactory factory2 = new DefaultSamlServiceFactory(); CertificateFactory certFactory = CertificateFactory .getInstance("X.509"); CertPath certPath = certFactory.generateCertPath(idmAccessor .getSAMLAuthorityChain()); SamlService service2 = factory2.createSamlService( idmClient.getTenantPrivateKey(VSPHERE_LOCAL_TENANT), SignatureAlgorithm.RSA_SHA256, SignatureAlgorithm.RSA_SHA256, idmClient.getEntityID(VSPHERE_LOCAL_TENANT), certPath); // now call it again with generated signature String vcdSignature = "YkgxdGRqY3FiVlQvUWRLTWRHUjF1V2dJeGJZa0pHNTJJ" + "NGd0RUsyUEtZTDAzcloyNWJ3dmxuLzg3TlNMN1JsSVhYc2NOSkxTaVZ4Mm" + "c4TjNxWTBTLzg2Z0dvYjZVdVU5elY2cEZtQnJ2N0ZFZFdndFJwVDlvZE5w" + "VVpaa3BxQ1ROZVU4STRQYTltMVVOTDB1TUp5ckJvaVBnY3dUbk5LTko4S0" + "dxMWNLMlVuWTZBZGlodW5XaXdTZW5CVDVVRjZ6MHFHWmZ2d25kM2dkTWl4" + "eHY2WWovVElXWUg5REZYN2FJN3R0a3RTaSs5dUhTbUViMTFWRElNcGhpbm" + "1rdldGT3VWWHIxWFR5RUNKYnpLNXhYR3ArZXZ1UGk2TzR1UDlEVjlVdjlU" + "V01uVVNPYkw1aExEUDFadC9Vbzl0S1MySWIwcUp0OGIzVzV2UzVDWVdlUU" + "JGRTBnPT0%3D"; vcdSignature = URLDecoder.decode(vcdSignature, "UTF-8"); vcdSignature = Shared.decodeString(vcdSignature); // just call verifySignature method and expect to not throw service2.verifySignature(message, vcdSignature);*/ }
From source file:org.loklak.api.aaa.LoginService.java
@Override public JSONObject serviceImpl(Query post, HttpServletResponse response, Authorization authorization, final JSONObjectWithDefault permissions) throws APIException { // login check for app if (post.get("checkLogin", false)) { JSONObject result = new JSONObject(); if (authorization.getIdentity().isEmail()) { result.put("loggedIn", true); result.put("message", "You are logged in as " + authorization.getIdentity().getName()); } else {/*from www.j a va 2 s . c o m*/ result.put("loggedIn", false); result.put("message", "Not logged in"); } return result; } // do logout if requested boolean logout = post.get("logout", false); boolean delete = post.get("delete", false); if (logout || delete) { // logout if requested // invalidate session post.getRequest().getSession().invalidate(); // delete cookie if set deleteLoginCookie(response); if (delete) { ClientCredential pwcredential = new ClientCredential(authorization.getIdentity()); delete = DAO.authentication.has(pwcredential.toString()); if (delete) DAO.authentication.remove(pwcredential.toString()); } JSONObject result = new JSONObject(); result.put("message", delete ? "Account deletion successful" : "Logout successful"); return result; } // check login type by checking which parameters are set boolean passwordLogin = false; boolean pubkeyHello = false; boolean pubkeyLogin = false; if (post.get("login", null) != null && post.get("password", null) != null && post.get("type", null) != null) { passwordLogin = true; } else if (post.get("login", null) != null && post.get("keyhash", null) != null) { pubkeyHello = true; } else if (post.get("sessionID", null) != null && post.get("response", null) != null) { pubkeyLogin = true; } else { throw new APIException(400, "Bad login parameters."); } // check if user is blocked because of too many invalid login attempts checkInvalidLogins(post, authorization, permissions); if (passwordLogin) { // do login via password String login = post.get("login", null); String password = post.get("password", null); String type = post.get("type", null); ClientCredential pwcredential = new ClientCredential(ClientCredential.Type.passwd_login, login); Authentication authentication = getAuthentication(post, authorization, pwcredential); ClientIdentity identity = authentication.getIdentity(); // check if the password is valid String passwordHash; String salt; try { passwordHash = authentication.getString("passwordHash"); salt = authentication.getString("salt"); } catch (Throwable e) { Log.getLog().info("Invalid login try for user: " + identity.getName() + " from host: " + post.getClientHost() + " : password or salt missing in database"); throw new APIException(422, "Invalid credentials"); } if (!passwordHash.equals(getHash(password, salt))) { // save invalid login in accounting object authorization.getAccounting().addRequest(this.getClass().getCanonicalName(), "invalid login"); Log.getLog().info("Invalid login try for user: " + identity.getName() + " via passwd from host: " + post.getClientHost()); throw new APIException(422, "Invalid credentials"); } JSONObject result = new JSONObject(); switch (type) { case "session": // create a browser session post.getRequest().getSession().setAttribute("identity", identity); break; case "cookie": // set a long living cookie // create random string as token String loginToken = createRandomString(30); // create cookie Cookie loginCookie = new Cookie("login", loginToken); loginCookie.setPath("/"); loginCookie.setMaxAge(defaultCookieTime.intValue()); // write cookie to database ClientCredential cookieCredential = new ClientCredential(ClientCredential.Type.cookie, loginToken); JSONObject user_obj = new JSONObject(); user_obj.put("id", identity.toString()); user_obj.put("expires_on", Instant.now().getEpochSecond() + defaultCookieTime); DAO.authentication.put(cookieCredential.toString(), user_obj, cookieCredential.isPersistent()); response.addCookie(loginCookie); break; case "access-token": // create and display an access token long valid_seconds; try { valid_seconds = post.get("valid_seconds", defaultAccessTokenExpireTime); } catch (Throwable e) { throw new APIException(400, "Invalid value for 'valid_seconds'"); } String token = createAccessToken(identity, valid_seconds); if (valid_seconds == -1) result.put("valid_seconds", "forever"); else result.put("valid_seconds", valid_seconds); result.put("access_token", token); break; default: throw new APIException(400, "Invalid type"); } Log.getLog().info( "login for user: " + identity.getName() + " via passwd from host: " + post.getClientHost()); result.put("message", "You are logged in as " + identity.getName()); return result; } else if (pubkeyHello) { // first part of pubkey login: if the key hash is known, create a challenge String login = post.get("login", null); String keyHash = post.get("keyhash", null); Authentication authentication = getAuthentication(post, authorization, new ClientCredential(ClientCredential.Type.passwd_login, login)); ClientIdentity identity = authentication.getIdentity(); if (!DAO.login_keys.has(identity.toString()) || !DAO.login_keys.getJSONObject(identity.toString()).has(keyHash)) throw new APIException(400, "Unknown key"); String challengeString = createRandomString(30); String newSessionID = createRandomString(30); ClientCredential credential = new ClientCredential(ClientCredential.Type.pubkey_challange, newSessionID); Authentication challenge_auth = new Authentication(credential, DAO.authentication); challenge_auth.setIdentity(identity); challenge_auth.put("activated", true); challenge_auth.put("challenge", challengeString); challenge_auth.put("key", DAO.login_keys.getJSONObject(identity.toString()).getString(keyHash)); challenge_auth.setExpireTime(60 * 10); JSONObject result = new JSONObject(); result.put("challenge", challengeString); result.put("sessionID", newSessionID); result.put("message", "Found valid key for this user. Sign the challenge with you public key and send it back, together with the sessionID"); return result; } else if (pubkeyLogin) { // second part of pubkey login: verify if the response to the challange is valid String sessionID = post.get("sessionID", null); String challangeResponse = post.get("response", null); Authentication authentication = getAuthentication(post, authorization, new ClientCredential(ClientCredential.Type.pubkey_challange, sessionID)); ClientIdentity identity = authentication.getIdentity(); String challenge = authentication.getString("challenge"); PublicKey key = IO.decodePublicKey(authentication.getString("key"), "RSA"); Signature sig; boolean verified; try { sig = Signature.getInstance("SHA256withRSA"); sig.initVerify(key); sig.update(challenge.getBytes()); verified = sig.verify(Base64.getDecoder().decode(challangeResponse)); } catch (NoSuchAlgorithmException e) { throw new APIException(400, "No such algorithm"); } catch (InvalidKeyException e) { throw new APIException(400, "Invalid key"); } catch (Throwable e) { throw new APIException(400, "Bad signature"); } if (verified) { long valid_seconds; try { valid_seconds = post.get("valid_seconds", defaultAccessTokenExpireTime); } catch (Throwable e) { throw new APIException(400, "Invalid value for 'valid_seconds'"); } String token = createAccessToken(identity, valid_seconds); JSONObject result = new JSONObject(); if (valid_seconds == -1) result.put("valid_seconds", "forever"); else result.put("valid_seconds", valid_seconds); result.put("access_token", token); return result; } else { authorization.getAccounting().addRequest(this.getClass().getCanonicalName(), "invalid login"); throw new APIException(400, "Bad Signature"); } } throw new APIException(500, "Server error"); }
From source file:ai.susi.server.api.aaa.LoginService.java
@Override public JSONObject serviceImpl(Query post, HttpServletResponse response, Authorization authorization, final JsonObjectWithDefault permissions) throws APIException { // login check for app if (post.get("checkLogin", false)) { JSONObject result = new JSONObject(); if (authorization.getIdentity().isEmail()) { result.put("loggedIn", true); result.put("message", "You are logged in as " + authorization.getIdentity().getName()); } else {//from w w w .j a va2 s .c om result.put("loggedIn", false); result.put("message", "Not logged in"); } return result; } // do logout if requested boolean logout = post.get("logout", false); boolean delete = post.get("delete", false); if (logout || delete) { // logout if requested // invalidate session post.getRequest().getSession().invalidate(); // delete cookie if set deleteLoginCookie(response); if (delete) { ClientCredential pwcredential = new ClientCredential(authorization.getIdentity()); delete = DAO.authentication.has(pwcredential.toString()); if (delete) DAO.authentication.remove(pwcredential.toString()); } JSONObject result = new JSONObject(); result.put("message", delete ? "Account deletion successful" : "Logout successful"); return result; } // check login type by checking which parameters are set boolean passwordLogin = false; boolean pubkeyHello = false; boolean pubkeyLogin = false; if (post.get("login", null) != null && post.get("password", null) != null && post.get("type", null) != null) { passwordLogin = true; } else if (post.get("login", null) != null && post.get("keyhash", null) != null) { pubkeyHello = true; } else if (post.get("sessionID", null) != null && post.get("response", null) != null) { pubkeyLogin = true; } else { throw new APIException(400, "Bad login parameters."); } // check if user is blocked because of too many invalid login attempts checkInvalidLogins(post, authorization, permissions); if (passwordLogin) { // do login via password String login = post.get("login", null); String password = post.get("password", null); String type = post.get("type", null); ClientCredential pwcredential = new ClientCredential(ClientCredential.Type.passwd_login, login); Authentication authentication = getAuthentication(post, authorization, pwcredential); ClientIdentity identity = authentication.getIdentity(); // check if the password is valid String passwordHash; String salt; try { passwordHash = authentication.getString("passwordHash"); salt = authentication.getString("salt"); } catch (Throwable e) { Log.getLog().info("Invalid login try for user: " + identity.getName() + " from host: " + post.getClientHost() + " : password or salt missing in database"); throw new APIException(422, "Invalid credentials"); } if (!passwordHash.equals(getHash(password, salt))) { // save invalid login in accounting object authorization.getAccounting().addRequest(this.getClass().getCanonicalName(), "invalid login"); Log.getLog().info("Invalid login try for user: " + identity.getName() + " via passwd from host: " + post.getClientHost()); throw new APIException(422, "Invalid credentials"); } JSONObject result = new JSONObject(); switch (type) { case "session": // create a browser session post.getRequest().getSession().setAttribute("identity", identity); break; case "cookie": // set a long living cookie // create random string as token String loginToken = createRandomString(30); // create cookie Cookie loginCookie = new Cookie("login", loginToken); loginCookie.setPath("/"); loginCookie.setMaxAge(defaultCookieTime.intValue()); // write cookie to database ClientCredential cookieCredential = new ClientCredential(ClientCredential.Type.cookie, loginToken); JSONObject user_obj = new JSONObject(); user_obj.put("id", identity.toString()); user_obj.put("expires_on", Instant.now().getEpochSecond() + defaultCookieTime); DAO.authentication.put(cookieCredential.toString(), user_obj, cookieCredential.isPersistent()); response.addCookie(loginCookie); break; case "access-token": // create and display an access token long valid_seconds; try { valid_seconds = post.get("valid_seconds", defaultAccessTokenExpireTime); } catch (Throwable e) { throw new APIException(400, "Invalid value for 'valid_seconds'"); } String token = createAccessToken(identity, valid_seconds); if (valid_seconds == -1) result.put("valid_seconds", "forever"); else result.put("valid_seconds", valid_seconds); result.put("access_token", token); break; default: throw new APIException(400, "Invalid type"); } Log.getLog().info( "login for user: " + identity.getName() + " via passwd from host: " + post.getClientHost()); result.put("message", "You are logged in as " + identity.getName()); return result; } else if (pubkeyHello) { // first part of pubkey login: if the key hash is known, create a challenge String login = post.get("login", null); String keyHash = post.get("keyhash", null); Authentication authentication = getAuthentication(post, authorization, new ClientCredential(ClientCredential.Type.passwd_login, login)); ClientIdentity identity = authentication.getIdentity(); if (!DAO.login_keys.has(identity.toString()) || !DAO.login_keys.getJSONObject(identity.toString()).has(keyHash)) throw new APIException(400, "Unknown key"); String challengeString = createRandomString(30); String newSessionID = createRandomString(30); ClientCredential credential = new ClientCredential(ClientCredential.Type.pubkey_challange, newSessionID); Authentication challenge_auth = new Authentication(credential, DAO.authentication); challenge_auth.setIdentity(identity); challenge_auth.put("activated", true); challenge_auth.put("challenge", challengeString); challenge_auth.put("key", DAO.login_keys.getJSONObject(identity.toString()).getString(keyHash)); challenge_auth.setExpireTime(60 * 10); JSONObject result = new JSONObject(); result.put("challenge", challengeString); result.put("sessionID", newSessionID); result.put("message", "Found valid key for this user. Sign the challenge with you public key and send it back, together with the sessionID"); return result; } else if (pubkeyLogin) { // second part of pubkey login: verify if the response to the challange is valid String sessionID = post.get("sessionID", null); String challangeResponse = post.get("response", null); Authentication authentication = getAuthentication(post, authorization, new ClientCredential(ClientCredential.Type.pubkey_challange, sessionID)); ClientIdentity identity = authentication.getIdentity(); String challenge = authentication.getString("challenge"); PublicKey key = IO.decodePublicKey(authentication.getString("key"), "RSA"); Signature sig; boolean verified; try { sig = Signature.getInstance("SHA256withRSA"); sig.initVerify(key); sig.update(challenge.getBytes()); verified = sig.verify(Base64.getDecoder().decode(challangeResponse)); } catch (NoSuchAlgorithmException e) { throw new APIException(400, "No such algorithm"); } catch (InvalidKeyException e) { throw new APIException(400, "Invalid key"); } catch (Throwable e) { throw new APIException(400, "Bad signature"); } if (verified) { long valid_seconds; try { valid_seconds = post.get("valid_seconds", defaultAccessTokenExpireTime); } catch (Throwable e) { throw new APIException(400, "Invalid value for 'valid_seconds'"); } String token = createAccessToken(identity, valid_seconds); JSONObject result = new JSONObject(); if (valid_seconds == -1) result.put("valid_seconds", "forever"); else result.put("valid_seconds", valid_seconds); result.put("access_token", token); return result; } else { authorization.getAccounting().addRequest(this.getClass().getCanonicalName(), "invalid login"); throw new APIException(400, "Bad Signature"); } } throw new APIException(500, "Server error"); }
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 ww 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.ejbca.core.protocol.cmp.CrmfRequestMessage.java
@Override public boolean verify() throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException { boolean ret = false; final ProofOfPossession pop = getReq().getPopo(); if (log.isDebugEnabled()) { log.debug("allowRaVerifyPopo: " + allowRaVerifyPopo); log.debug("pop.getRaVerified(): " + (pop.getType() == ProofOfPossession.TYPE_RA_VERIFIED)); }/*from w w w. ja va 2s. co m*/ if (allowRaVerifyPopo && (pop.getType() == ProofOfPossession.TYPE_RA_VERIFIED)) { ret = true; } else if (pop.getType() == ProofOfPossession.TYPE_SIGNING_KEY) { try { final POPOSigningKey sk = (POPOSigningKey) pop.getObject(); final POPOSigningKeyInput pski = sk.getPoposkInput(); ASN1Encodable protObject = pski; // Use of POPOSigningKeyInput or not, as described in RFC4211, section 4.1. if (pski == null) { if (log.isDebugEnabled()) { log.debug("Using CertRequest as POPO input because POPOSigningKeyInput is missing."); } protObject = getReq().getCertReq(); } else { // Assume POPOSigningKeyInput with the public key and name, MUST be the same as in the request according to RFC4211 if (log.isDebugEnabled()) { log.debug("Using POPOSigningKeyInput as POPO input."); } final CertRequest req = getReq().getCertReq(); // If subject is present in cert template it must be the same as in POPOSigningKeyInput final X500Name subject = req.getCertTemplate().getSubject(); if (subject != null && !subject.toString().equals(pski.getSender().getName().toString())) { log.info("Subject '" + subject.toString() + "', is not equal to '" + pski.getSender().toString() + "'."); protObject = null; // pski is not a valid protection object } // If public key is present in cert template it must be the same as in POPOSigningKeyInput final SubjectPublicKeyInfo pk = req.getCertTemplate().getPublicKey(); if (pk != null && !Arrays.areEqual(pk.getEncoded(), pski.getPublicKey().getEncoded())) { log.info( "Subject key in cert template, is not equal to subject key in POPOSigningKeyInput."); protObject = null; // pski is not a valid protection object } } // If a protectObject is present we extract the bytes and verify it if (protObject != null) { final ByteArrayOutputStream bao = new ByteArrayOutputStream(); new DEROutputStream(bao).writeObject(protObject); final byte[] protBytes = bao.toByteArray(); final AlgorithmIdentifier algId = sk.getAlgorithmIdentifier(); if (log.isDebugEnabled()) { log.debug( "POP protection bytes length: " + (protBytes != null ? protBytes.length : "null")); log.debug("POP algorithm identifier is: " + algId.getAlgorithm().getId()); } final Signature sig = Signature.getInstance(algId.getAlgorithm().getId(), "BC"); sig.initVerify(getRequestPublicKey()); sig.update(protBytes); final DERBitString bs = sk.getSignature(); ret = sig.verify(bs.getBytes()); if (log.isDebugEnabled()) { log.debug("POP verify returns: " + ret); } } } catch (IOException e) { log.error("Error encoding CertReqMsg: ", e); } catch (SignatureException e) { log.error("SignatureException verifying POP: ", e); } } return ret; }
From source file:org.apache.camel.component.crypto.processor.VerifyingProcessor.java
public void process(Exchange exchange) throws Exception { Signature signer = createSignatureService(); Certificate cert = getCertificate(exchange); if (cert == null) { PublicKey pk = getPublicKeyOrCertificateFromHeader(exchange, PublicKey.class, config.getPublicKey()); if (pk == null) { throw new IllegalStateException(String.format( "Cannot verify signature as no Public Key or Certificate has been supplied." + " Either supply one in the route definition or via the message header '%s'", DigitalSignatureConstants.SIGNATURE_PUBLIC_KEY_OR_CERT)); }//from w w w .j a va2 s. c o m signer.initVerify(pk); } else { signer.initVerify(cert); } calculateSignature(exchange, signer); byte[] signature = getSignatureFromExchange(exchange); if (!signer.verify(signature)) { throw new SignatureException("Cannot verify signature of exchange"); } clearMessageHeaders(exchange.getIn()); }
From source file:be.fedict.eid.applet.service.impl.handler.SignatureDataMessageHandler.java
public Object handleMessage(SignatureDataMessage message, Map<String, String> httpHeaders, HttpServletRequest request, HttpSession session) throws ServletException { LOG.debug("signature data message received"); byte[] signatureValue = message.signatureValue; List<X509Certificate> certificateChain = message.certificateChain; if (certificateChain.isEmpty()) { throw new ServletException("certificate chain is empty"); }/*from ww w .ja v a2s . c om*/ X509Certificate signingCertificate = certificateChain.get(0); if (null == signingCertificate) { throw new ServletException("non-repudiation certificate missing"); } LOG.debug("non-repudiation signing certificate: " + signingCertificate.getSubjectX500Principal()); for (X509Certificate certificate : certificateChain) { LOG.debug("signing x509 cert: " + certificate.getSubjectX500Principal()); } PublicKey signingPublicKey = signingCertificate.getPublicKey(); /* * Verify the signature. */ String digestAlgo = SignatureDataMessageHandler.getDigestAlgo(session); byte[] expectedDigestValue = SignatureDataMessageHandler.getDigestValue(session); if (digestAlgo.endsWith("-PSS")) { LOG.debug("verifying RSA/PSS signature"); try { Signature signature = Signature.getInstance("RAWRSASSA-PSS", BouncyCastleProvider.PROVIDER_NAME); if ("SHA-256-PSS".equals(digestAlgo)) { LOG.debug("RSA/PSS SHA256"); signature.setParameter( new PSSParameterSpec("SHA-256", "MGF1", new MGF1ParameterSpec("SHA-256"), 32, 1)); } signature.initVerify(signingPublicKey); signature.update(expectedDigestValue); boolean result = signature.verify(signatureValue); if (false == result) { throw new SecurityException("signature incorrect"); } } catch (Exception e) { LOG.debug("signature verification error: " + e.getMessage(), e); throw new ServletException("signature verification error: " + e.getMessage(), e); } } else { try { Signature signature = Signature.getInstance("RawRSA", BouncyCastleProvider.PROVIDER_NAME); signature.initVerify(signingPublicKey); ByteArrayOutputStream digestInfo = new ByteArrayOutputStream(); if ("SHA-1".equals(digestAlgo) || "SHA1".equals(digestAlgo)) { digestInfo.write(SHA1_DIGEST_INFO_PREFIX); } else if ("SHA-224".equals(digestAlgo)) { digestInfo.write(SHA224_DIGEST_INFO_PREFIX); } else if ("SHA-256".equals(digestAlgo)) { digestInfo.write(SHA256_DIGEST_INFO_PREFIX); } else if ("SHA-384".equals(digestAlgo)) { digestInfo.write(SHA384_DIGEST_INFO_PREFIX); } else if ("SHA-512".equals(digestAlgo)) { digestInfo.write(SHA512_DIGEST_INFO_PREFIX); } else if ("RIPEMD160".equals(digestAlgo)) { digestInfo.write(RIPEMD160_DIGEST_INFO_PREFIX); } else if ("RIPEMD128".equals(digestAlgo)) { digestInfo.write(RIPEMD128_DIGEST_INFO_PREFIX); } else if ("RIPEMD256".equals(digestAlgo)) { digestInfo.write(RIPEMD256_DIGEST_INFO_PREFIX); } digestInfo.write(expectedDigestValue); signature.update(digestInfo.toByteArray()); boolean result = signature.verify(signatureValue); if (false == result) { AuditService auditService = this.auditServiceLocator.locateService(); if (null != auditService) { String remoteAddress = request.getRemoteAddr(); auditService.signatureError(remoteAddress, signingCertificate); } throw new SecurityException("signature incorrect"); } } catch (Exception e) { LOG.debug("signature verification error: " + e.getMessage()); throw new ServletException("signature verification error: " + e.getMessage(), e); } } AuditService auditService = this.auditServiceLocator.locateService(); if (null != auditService) { String userId = UserIdentifierUtil.getUserId(signingCertificate); auditService.signed(userId); } SignatureService signatureService = this.signatureServiceLocator.locateService(); try { signatureService.setHttpSessionObject(request.getSession()); signatureService.postSign(signatureValue, certificateChain); } catch (ExpiredCertificateSecurityException e) { return new FinishedMessage(ErrorCode.CERTIFICATE_EXPIRED); } catch (RevokedCertificateSecurityException e) { return new FinishedMessage(ErrorCode.CERTIFICATE_REVOKED); } catch (TrustCertificateSecurityException e) { return new FinishedMessage(ErrorCode.CERTIFICATE_NOT_TRUSTED); } catch (CertificateSecurityException e) { return new FinishedMessage(ErrorCode.CERTIFICATE); } catch (Exception e) { /* * We don't want to depend on the full JavaEE profile in this * artifact. */ if ("javax.ejb.EJBException".equals(e.getClass().getName())) { Exception exception; try { Method getCausedByExceptionMethod = e.getClass().getMethod("getCausedByException", new Class[] {}); exception = (Exception) getCausedByExceptionMethod.invoke(e, new Object[] {}); } catch (Exception e2) { LOG.debug("error: " + e.getMessage(), e); throw new SecurityException("error retrieving the root cause: " + e2.getMessage()); } if (exception instanceof ExpiredCertificateSecurityException) { return new FinishedMessage(ErrorCode.CERTIFICATE_EXPIRED); } if (exception instanceof RevokedCertificateSecurityException) { return new FinishedMessage(ErrorCode.CERTIFICATE_REVOKED); } if (exception instanceof TrustCertificateSecurityException) { return new FinishedMessage(ErrorCode.CERTIFICATE_NOT_TRUSTED); } if (exception instanceof CertificateSecurityException) { return new FinishedMessage(ErrorCode.CERTIFICATE); } } throw new SecurityException("signature service error: " + e.getMessage(), e); } return new FinishedMessage(); }
From source file:be.fedict.eid.applet.service.impl.handler.IdentityDataMessageHandler.java
private void verifySignature(String signAlgo, byte[] signatureData, PublicKey publicKey, HttpServletRequest request, byte[]... data) throws ServletException { Signature signature; try {/*from w ww . j a v a2s. c o m*/ signature = Signature.getInstance(signAlgo); } catch (NoSuchAlgorithmException e) { throw new ServletException("algo error: " + e.getMessage(), e); } try { signature.initVerify(publicKey); } catch (InvalidKeyException e) { throw new ServletException("key error: " + e.getMessage(), e); } try { for (byte[] dataItem : data) { signature.update(dataItem); } boolean result = signature.verify(signatureData); if (false == result) { AuditService auditService = this.auditServiceLocator.locateService(); if (null != auditService) { String remoteAddress = request.getRemoteAddr(); auditService.identityIntegrityError(remoteAddress); } throw new ServletException("signature incorrect"); } } catch (SignatureException e) { AuditService auditService = this.auditServiceLocator.locateService(); if (null != auditService) { String remoteAddress = request.getRemoteAddr(); auditService.identityIntegrityError(remoteAddress); } throw new ServletException("signature error: " + e.getMessage(), e); } }