List of usage examples for org.apache.commons.codec.digest DigestUtils sha1
public static byte[] sha1(String data)
From source file:com.gitblit.HtpasswdUserService.java
/** * Authenticate a user based on a username and password. * * If the account is determined to be a local account, authentication * will be done against the locally stored password. * Otherwise, the configured htpasswd file is read. All current output options * of htpasswd are supported: clear text, crypt(), Apache MD5 and unsalted SHA-1. * * @param username/*from w w w . j a v a 2s . c o m*/ * @param password * @return a user object or null */ @Override public UserModel authenticate(String username, char[] password) { if (isLocalAccount(username)) { // local account, bypass htpasswd authentication return super.authenticate(username, password); } read(); String storedPwd = htUsers.get(username); if (storedPwd != null) { boolean authenticated = false; final String passwd = new String(password); // test Apache MD5 variant encrypted password if (storedPwd.startsWith("$apr1$")) { if (storedPwd.equals(Md5Crypt.apr1Crypt(passwd, storedPwd))) { logger.debug("Apache MD5 encoded password matched for user '" + username + "'"); authenticated = true; } } // test unsalted SHA password else if (storedPwd.startsWith("{SHA}")) { String passwd64 = Base64.encodeBase64String(DigestUtils.sha1(passwd)); if (storedPwd.substring("{SHA}".length()).equals(passwd64)) { logger.debug("Unsalted SHA-1 encoded password matched for user '" + username + "'"); authenticated = true; } } // test libc crypt() encoded password else if (supportCryptPwd() && storedPwd.equals(Crypt.crypt(passwd, storedPwd))) { logger.debug("Libc crypt encoded password matched for user '" + username + "'"); authenticated = true; } // test clear text else if (supportPlaintextPwd() && storedPwd.equals(passwd)) { logger.debug("Clear text password matched for user '" + username + "'"); authenticated = true; } if (authenticated) { logger.debug("Htpasswd authenticated: " + username); UserModel user = getUserModel(username); if (user == null) { // create user object for new authenticated user user = new UserModel(username); } // create a user cookie if (StringUtils.isEmpty(user.cookie) && !ArrayUtils.isEmpty(password)) { user.cookie = StringUtils.getSHA1(user.username + passwd); } // Set user attributes, hide password from backing user service. user.password = Constants.EXTERNAL_ACCOUNT; user.accountType = getAccountType(); // Push the looked up values to backing file super.updateUserModel(user); return user; } } return null; }
From source file:fathom.realm.htpasswd.HtpasswdRealm.java
/** * htpasswd supports a few other password encryption schemes than the StandardCredentialsRealm. * * @param requestCredentials/*from w ww. j a v a 2 s . co m*/ * @param storedCredentials * @return true if the request password validates against the stored password */ @Override protected boolean validatePassword(StandardCredentials requestCredentials, StandardCredentials storedCredentials) { final String storedPassword = storedCredentials.getPassword(); final String username = requestCredentials.getUsername(); final String password = requestCredentials.getPassword(); boolean authenticated = false; // test Apache MD5 variant encrypted password if (storedPassword.startsWith("$apr1$")) { if (storedPassword.equals(Md5Crypt.apr1Crypt(password, storedPassword))) { log.trace("Apache MD5 encoded password matched for user '{}'", username); authenticated = true; } } // test Unsalted SHA password else if (storedPassword.startsWith("{SHA}")) { String password64 = Base64.encodeBase64String(DigestUtils.sha1(password)); if (storedPassword.substring("{SHA}".length()).equals(password64)) { log.trace("Unsalted SHA-1 encoded password matched for user '{}'", username); authenticated = true; } } // test Libc Crypt password else if (!isAllowClearTextPasswords() && storedPassword.equals(Crypt.crypt(password, storedPassword))) { log.trace("Libc crypt encoded password matched for user '{}'", username); authenticated = true; } // test Clear Text password else if (isAllowClearTextPasswords() && storedPassword.equals(password)) { log.trace("Clear text password matched for user '{}'", username); authenticated = true; } return authenticated; }
From source file:edu.kit.dama.util.CryptUtil.java
/** * Convert the provided string to a SHA1 representation and return it as hex * string./*w ww. j a v a 2 s .co m*/ * * @param pString The plain string. * * @return The target string as SHA1toHex(SHA1(pString)). */ public static String stringToSHA1(String pString) { return DigestUtils.sha1Hex(DigestUtils.sha1(pString)); }
From source file:de.elomagic.carafile.client.CaraFileClientTest.java
@Test public void testDownload2() throws Exception { Random random = new Random(); random.nextBytes(data0);/*w w w.j ava 2 s. c o m*/ random.nextBytes(data1); chunkId0 = Hex.encodeHexString(DigestUtils.sha1(data0)); chunkId1 = Hex.encodeHexString(DigestUtils.sha1(data1)); MessageDigest messageDigest = DigestUtils.getSha1Digest(); messageDigest.update(data0); messageDigest.update(data1); id = Hex.encodeHexString(messageDigest.digest()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); client.setRegistryURI(getURI()).downloadFile(id, baos); Assert.assertArrayEquals(data0, Arrays.copyOf(baos.toByteArray(), DEFAULT_PIECE_SIZE)); Assert.assertArrayEquals(data1, Arrays.copyOfRange(baos.toByteArray(), DEFAULT_PIECE_SIZE, DEFAULT_PIECE_SIZE + 128)); }
From source file:com.thoughtworks.go.util.FileUtil.java
public static String sha1Digest(File file) { try (InputStream is = new BufferedInputStream(new FileInputStream(file))) { byte[] hash = DigestUtils.sha1(is); return Base64.getEncoder().encodeToString(hash); } catch (IOException e) { throw ExceptionUtils.bomb(e); }/* w w w . ja v a 2 s .c o m*/ }
From source file:com.bernardomg.example.swss.test.util.factory.SecureSoapMessages.java
/** * Generates the digest value for the SOAP secure header. * <p>//from ww w. ja v a2 s . c o m * This is a codified password, with the help of the date and nonce values. * Both of these values should be found on the SOAP secure header. * * @param password * password to digest * @param date * date used on the SOAP header * @param nonce * nonce used on the SOAP header * @return the digested password * @throws UnsupportedEncodingException * if the UTF-8 encoding is not supported */ private static final String generateDigest(final String password, final String date, final String nonce) throws UnsupportedEncodingException { final ByteBuffer buf; // Buffers storing the data to digest byte[] toHash; // Bytes to generate the hash // Fills buffer with data to digest buf = ByteBuffer.allocate(1000); buf.put(Base64.decodeBase64(nonce)); buf.put(date.getBytes("UTF-8")); buf.put(password.getBytes("UTF-8")); // Initializes hash bytes to the correct size toHash = new byte[buf.position()]; buf.rewind(); // Copies bytes from the buffer to the hash bytes buf.get(toHash); return Base64.encodeBase64String(DigestUtils.sha1(toHash)); }
From source file:com.bittorrent.mpetazzoni.common.Torrent.java
public static byte[] hash(byte[] data) { return DigestUtils.sha1(data); }
From source file:de.tum.frm2.nicos_android.nicos.NicosClient.java
public void connect(ConnectionData connData, Object[] eventmask) throws RuntimeException { if (connected) { throw new RuntimeException("client already connected"); }/* www . j ava 2 s . c o m*/ disconnecting = false; SocketAddress sockaddr; try { // If ANY code of this scope failes, communication is entirely impossible. // That means, no need to catch all exceptions one by one. InetAddress addr = InetAddress.getByName(connData.getHost()); sockaddr = new InetSocketAddress(addr, connData.getPort()); // Initialize empty socket. socket = new Socket(); // Connects this socket to the server with a specified timeout value // If timeout occurs, SocketTimeoutException is thrown socket.connect(sockaddr, TIMEOUT); socketOut = socket.getOutputStream(); socketIn = socket.getInputStream(); // Write client identification: we are a new client socketOut.write(client_id); } catch (Exception e) { String msg; if (e instanceof IOException) { // "null reference" error messages won't help the user. msg = "Socket communication failed (server not responding)."; } else { msg = "Server connection failed: " + e.getMessage() + "."; } signal("failed", msg); return; } // read banner try { TupleOfTwo<Byte, Object> response = _read(); byte ret = response.getFirst(); if (ret != daemon.STX) { throw new ProtocolError("invalid response format"); } nicosBanner = (HashMap) response.getSecond(); if (!nicosBanner.containsKey("daemon_version")) { throw new ProtocolError("daemon version missing from response"); } int daemon_proto = (int) nicosBanner.get("protocol_version"); if (!daemon.isProtoVersionCompatible(daemon_proto)) { throw new ProtocolError("daemon uses protocol " + String.valueOf(daemon_proto) + ", but this client requires protocol " + String.valueOf(daemon.PROTO_VERSIONS[0])); } } catch (Exception e) { signal("failed", "Server(" + connData.getHost() + ":" + String.valueOf(connData.getPort()) + ") handshake failed: " + e.getMessage()); return; } // log-in sequence char[] password = connData.getPassword(); Object unwrap = nicosBanner.get("pw_hashing"); String pw_hashing = "sha1"; if (unwrap != null) { pw_hashing = unwrap.toString(); } String encryptedPassword = null; boolean supportsRSA = false; try { String rsaSupportString = pw_hashing.substring(0, 4); supportsRSA = rsaSupportString.equals("rsa,"); } catch (StringIndexOutOfBoundsException e) { // Does not start with "rsa," -> does not support RSA encryption. // boolean supportsRSA stays at false. } if (supportsRSA) { byte[] keyBytes = Base64.decode(nicosBanner.get("rsakey").toString(), Base64.DEFAULT); String publicKeyString = new String(keyBytes, StandardCharsets.UTF_8); PublicKey publicKey = extractPublicKey(publicKeyString); Cipher cipher = null; try { cipher = Cipher.getInstance("RSA/None/PKCS1Padding", "BC"); } catch (NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException e) { // Cannot happen. } try { if (cipher != null) { cipher.init(Cipher.ENCRYPT_MODE, publicKey); } else { throw new InvalidKeyException(); } } catch (InvalidKeyException e) { throw new RuntimeException("The server's RSA key is invalid or incompatible."); } byte[] encrypted; try { encrypted = cipher.doFinal(String.valueOf(password).getBytes()); } catch (IllegalBlockSizeException | BadPaddingException e) { e.printStackTrace(); encrypted = new byte[0]; } encryptedPassword = "RSA:" + Base64.encodeToString(encrypted, Base64.DEFAULT); } if (pw_hashing.equals("sha1")) { encryptedPassword = new String(Hex.encodeHex(DigestUtils.sha1(String.valueOf(password)))); } else if (pw_hashing.equals("md5")) { encryptedPassword = new String(Hex.encodeHex(DigestUtils.md5(String.valueOf(password)))); } HashMap<String, String> credentials = new HashMap<>(); credentials.put("login", connData.getUser()); credentials.put("passwd", encryptedPassword); credentials.put("display", ""); // Server requires credentials to be wrapped in a tuple with 1 item // e.g. python: payload = (credentials,) // Pyrolite library matches java.lang.Object arrays to tuples with the array's length. Object[] data = { credentials }; Object untypedAuthResponse = ask("authenticate", data); if (untypedAuthResponse == null) { return; } // Login was successful. HashMap authResponse = (HashMap) untypedAuthResponse; user_level = (int) authResponse.get("user_level"); if (eventmask != null) { tell("eventmask", eventmask); } // connect to event port eventSocket = new Socket(); try { eventSocket.connect(sockaddr); OutputStream eventSocketOut = eventSocket.getOutputStream(); eventSocketIn = eventSocket.getInputStream(); eventSocketOut.write(client_id); } catch (IOException e) { signal("failed", "Event connection failed: " + e.getMessage() + ".", e); return; } // Start event handler final Thread event_thread = new Thread(new Runnable() { @Override public void run() { // equals event_handler. event_handler(); } }); event_thread.start(); connected = true; viewonly = connData.getViewonly(); signal("connected"); }
From source file:fr.letroll.ttorrentandroid.common.Torrent.java
@Nonnull public static byte[] hash(@Nonnull byte[] data) { return DigestUtils.sha1(data); }
From source file:jproxy.ProxyControl.java
public String[] getCertificateDetails() { if (isDynamicMode()) { try {/*from w w w. ja v a2 s .c o m*/ X509Certificate caCert = (X509Certificate) keyStore.getCertificate(KeyToolUtils.getRootCAalias()); if (caCert == null) { return new String[] { "Could not find certificate" }; } return new String[] { caCert.getSubjectX500Principal().toString(), "Fingerprint(SHA1): " + JOrphanUtils.baToHexString(DigestUtils.sha1(caCert.getEncoded()), ' '), "Created: " + caCert.getNotBefore().toString() }; } catch (GeneralSecurityException e) { log.error("Problem reading root CA from keystore", e); return new String[] { "Problem with root certificate", e.getMessage() }; } } return null; // should not happen }