List of usage examples for java.security MessageDigest isEqual
public static boolean isEqual(byte[] digesta, byte[] digestb)
From source file:org.ebayopensource.fidouaf.res.util.NotaryImpl.java
public boolean verify(String signData, String signature) { try {//from ww w .j av a2 s. c o m return MessageDigest.isEqual(Base64.decodeBase64(signature), HMAC.sign(signData, hmacSecret)); } catch (Exception e) { logger.info(e.toString()); } return false; }
From source file:io.pivotal.cla.security.GitHubSignature.java
@SneakyThrows public boolean check(String gitHubSignature, String body) { if (gitHubSignature == null || !gitHubSignature.startsWith(SIGNATURE_PREFIX)) { return false; }//from w w w. j av a 2s . c o m AccessToken expectedToken = accessTokens.findOne(AccessToken.CLA_ACCESS_TOKEN_ID); if (expectedToken == null) { return false; } String providedHmac = gitHubSignature.substring(SIGNATURE_PREFIX.length()); byte[] providedHmacBytes = Hex.decode(providedHmac); byte[] expectedBytes = sign(body, expectedToken.getToken()); return MessageDigest.isEqual(providedHmacBytes, expectedBytes); }
From source file:org.sakaiproject.kernel.user.AuthenticationCache.java
public Authentication getAuthentication(IdPrincipal idPrincipal) throws SecurityException { Authentication auth = null;/*from www . j a va2 s. c o m*/ try { AuthenticationRecord record = authCache.get(idPrincipal.getIdentifier()); if (record.withpassword) { if (idPrincipal instanceof IdPwPrincipal) { IdPwPrincipal idPwPrincipal = (IdPwPrincipal) idPrincipal; if (MessageDigest.isEqual(record.encodedPassword, getEncrypted(idPwPrincipal.getPassword()))) { if (record.authentication == null) { if (debug) { LOG.debug( "getAuthentication: replaying authentication failure for authenticationId=" + idPrincipal.getIdentifier()); } throw new SecurityException("repeated invalid login"); } else { if (debug) { LOG.debug("getAuthentication: returning record for authenticationId=" + idPrincipal.getIdentifier()); } auth = record.authentication; } } else { // Since the passwords didn't match, we're no longer getting // repeats, // and so the record should be removed. if (debug) { LOG.debug("getAuthentication: record for authenticationId=" + idPrincipal.getIdentifier() + " failed password check"); } authCache.remove(idPrincipal.getIdentifier()); } } } } catch (NullPointerException e) { // this is ok and generally expected to indicate the value is not in the // cache auth = null; } return auth; }
From source file:tests.unit.util.bin.DumpTestCase.java
/** * @throws Exception//w w w .jav a2 s . c om */ public void testDumpRec() throws Exception { File tmp = new File(System.getProperty("java.io.tmpdir"), "TestDump.dump"); try { FileUtils.deleteQuietly(tmp); byte[] dataFile = BinaryUtils.readFileAsBytesFromCP("start.png"); Dump dump = new Dump(dataFile, Dump.UNBOUNDED); OutputStream out = new FileOutputStream(tmp); try { dump.dump(out); } finally { out.flush(); out.close(); } dump = new Dump(new FileReader(tmp)); byte[] dataRec = null; try { dataRec = dump.recoverToBytes(); } finally { out.close(); } MessageDigest md = MessageDigest.getInstance("SHA"); byte[] dFile = md.digest(dataFile); byte[] dRec = md.digest(dataRec); boolean result = MessageDigest.isEqual(dFile, dRec); System.out.println("Binary Dump conversion succesfull: " + result); assertTrue("Binary Dump conversion failed", result); } finally { FileUtils.deleteQuietly(tmp); } }
From source file:org.nuxeo.ecm.directory.PasswordHelper.java
/** * Verify a password against a hashed password. * <p>/*from ww w . j a va 2 s. co m*/ * If the hashed password is {@code null} then the verification always fails. * * @param password the password to verify * @param hashedPassword the hashed password * @return {@code true} if the password matches */ public static boolean verifyPassword(String password, String hashedPassword) { if (hashedPassword == null) { return false; } String digestalg; int len; if (hashedPassword.startsWith(HSSHA)) { digestalg = SHA1; len = 20; } else if (hashedPassword.startsWith(HSMD5)) { digestalg = MD5; len = 16; } else { return hashedPassword.equals(password); } String digest = hashedPassword.substring(6); byte[] bytes = Base64.decodeBase64(digest); if (bytes == null) { // invalid base64 return false; } if (bytes.length < len + 2) { // needs hash + at least two bytes of salt return false; } byte[] hash = new byte[len]; byte[] salt = new byte[bytes.length - len]; System.arraycopy(bytes, 0, hash, 0, hash.length); System.arraycopy(bytes, hash.length, salt, 0, salt.length); return MessageDigest.isEqual(hash, digestWithSalt(password, salt, digestalg)); }
From source file:org.sakaiproject.user.impl.AuthenticationCache.java
public Authentication getAuthentication(String authenticationId, String password) throws AuthenticationException { Authentication auth = null;//from ww w. ja v a2s.c om AuthenticationRecord record = (AuthenticationRecord) authCache.get(authenticationId); if (record != null) { byte[] salt = new byte[saltLength]; System.arraycopy(record.encodedPassword, 0, salt, 0, salt.length); byte[] encodedPassword = getEncrypted(password, salt); if (MessageDigest.isEqual(record.encodedPassword, encodedPassword)) { if (record.authentication == null) { if (log.isDebugEnabled()) log.debug("getAuthentication: replaying authentication failure for authenticationId=" + authenticationId); throw new AuthenticationException("repeated invalid login"); } else { if (log.isDebugEnabled()) log.debug("getAuthentication: returning record for authenticationId=" + authenticationId); auth = record.authentication; } } else { // Since the passwords didn't match, we're no longer getting repeats, // and so the record should be removed. if (log.isDebugEnabled()) log.debug("getAuthentication: record for authenticationId=" + authenticationId + " failed password check"); authCache.remove(authenticationId); } } return auth; }
From source file:fr.aliacom.obm.ldap.PasswordHandler.java
public synchronized boolean verify(String digest, String password) throws NoSuchAlgorithmException { String alg = null;/*from w w w. j ava 2 s . c o m*/ int size = 0; if (digest.regionMatches(true, 0, "{CRYPT}", 0, 7)) { digest = digest.substring(7); return UnixCrypt.matches(digest, password); } else if (digest.regionMatches(true, 0, "{SHA}", 0, 5)) { digest = digest.substring(5); // ignore the label alg = "SHA-1"; size = 20; } else if (digest.regionMatches(true, 0, "{SSHA}", 0, 6)) { digest = digest.substring(6); // ignore the label alg = "SHA-1"; size = 20; } else if (digest.regionMatches(true, 0, "{MD5}", 0, 5)) { digest = digest.substring(5); // ignore the label alg = "MD5"; size = 16; } else if (digest.regionMatches(true, 0, "{SMD5}", 0, 6)) { digest = digest.substring(6); // ignore the label alg = "MD5"; size = 16; } // TODO: vrifier si le synchronized que j'ai ajout est ncessaire MessageDigest msgDigest = MessageDigest.getInstance(alg); byte[][] hs = split(Base64.decodeBase64(digest), size); byte[] hash = hs[0]; byte[] salt = hs[1]; msgDigest.reset(); msgDigest.update(password.getBytes(Charsets.UTF_8)); msgDigest.update(salt); byte[] pwhash = msgDigest.digest(); return MessageDigest.isEqual(hash, pwhash); }
From source file:org.duracloud.chunk.ChunkableContentTest.java
private void verifyTotalChunkChecksum() throws Exception { MessageDigest md5 = MessageDigest.getInstance(Algorithm.MD5.name()); DigestInputStream istream;//from www . j av a2 s .co m for (File chunk : chunkFiles) { istream = new DigestInputStream(new FileInputStream(chunk), md5); read(istream); md5 = istream.getMessageDigest(); IOUtils.closeQuietly(istream); } Assert.assertNotNull(md5); Assert.assertTrue(MessageDigest.isEqual(contentChecksum.digest(), md5.digest())); }
From source file:useraccess.ejb.SessionBean.java
/** * Validates user credentials for login into the application * @param credentials the login credentials * @return the user data for the session if login is sucessful. * @throws LoginException if there is any error in the credentials or user status * is different from normal/*from w ww. java2 s. c o m*/ */ @Override public UserBean validateUserCredentials(LoginBean credentials) throws LoginException { try { logger.info("Beginning of user login validation, business tier."); //Validates login existence Credential cred = this.findCredentialByLogin(credentials.getLogin()); //Validates password //String passwdUTF=new String (cred.getPassword().getBytes(), Charset.forName("UTF-8")); if (!MessageDigest.isEqual( this.encrypter.encrypt(credentials.getPassword().getBytes(), "SHA-256").getBytes(), cred.getPassword().getBytes())) throw new LoginException("Contrasea incorrecta."); //Checks the user status User user = (User) em.find(User.class, cred.getId()); Status status = (Status) em.createNamedQuery("findStatusByDescription") .setParameter("description", "normal").getSingleResult(); if (!user.getStatus().equals(status)) throw new LoginException( "El estado del usuario es incorrecto:" + user.getStatus().getDescription()); //Updates user last access date cred.setLastAccess(new Date()); //sets user data for the session and returns this.user.setId(user.getId()); this.user.setName(user.getName()); this.user.setSurname(user.getSurname()); this.user.setDni(cred.getLogin()); this.user.setEmail(user.getEmail()); this.user.setPosition(user.getPosition()); this.user.setTitle(user.getTitle()); this.user.setLastAccess(cred.getLastAccess()); Iterator it = user.getSocialProfiles().iterator(); Vector<SocialProfileBean> userProfiles = new Vector<SocialProfileBean>(); while (it.hasNext()) { SocialProfile profile = (SocialProfile) it.next(); SocialProfileBean newProfile = new SocialProfileBean(profile.getNetwork(), profile.getAccount()); userProfiles.add(newProfile); } this.user.setSocialProfiles(userProfiles); logger.info("End of user login validation, business tier."); return this.user; } catch (Exception e) { throw new LoginException(e.getMessage()); } }
From source file:org.whispersystems.claserver.PullRequestValidationServlet.java
/** * This is the endpoint for the github webhook */// w w w. j a v a 2 s .c om protected void doPost(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException { String xHubSig = request.getHeader("X-Hub-Signature"); StringWriter writer = new StringWriter(); mapper.writeValue(writer, request.getParameterMap()); String body = CharStreams.toString(request.getReader()); GithubPullEvent event = mapper.readValue(mapper.getJsonFactory().createJsonParser(body), GithubPullEvent.class); try { Mac mac = Mac.getInstance("HmacSHA1"); SecretKeySpec secret = new SecretKeySpec(config.githubSecret.getBytes("UTF-8"), "HmacSHA1"); mac.init(secret); byte[] digest = mac.doFinal(body.getBytes()); String hmac = String.format("sha1=%s", Hex.encodeHexString(digest)); if (MessageDigest.isEqual(hmac.getBytes(), xHubSig.getBytes())) { updateStatus(config, event.pull_request); } else { logger.warning("Invalid request signature"); } } catch (NoSuchAlgorithmException | InvalidKeyException e) { e.printStackTrace(); } }