Java Code Examples for java.security.MessageDigest

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project agile, under directory /agile-api/src/main/java/org/headsupdev/agile/api/util/.

Source file: HashUtil.java

  23 
vote

public static String getMD5Hex(String in){
  MessageDigest messageDigest;
  try {
    messageDigest=java.security.MessageDigest.getInstance("MD5");
    messageDigest.update(in.getBytes(),0,in.length());
    return new BigInteger(1,messageDigest.digest()).toString(16);
  }
 catch (  NoSuchAlgorithmException e) {
    e.printStackTrace();
  }
  return "";
}
 

Example 2

From project ajah, under directory /ajah-util/src/main/java/com/ajah/util/data/.

Source file: HashUtils.java

  19 
vote

/** 
 * Creates a SHA-1 digest of byte array and returns it as a hexadecimal number.
 * @param data The data to digest.
 * @return The hexadecimal result of the digest.
 */
public static String sha1Hex(final byte[] data){
  AjahUtils.requireParam(data,"data");
  try {
    final MessageDigest md=MessageDigest.getInstance("SHA-1");
    md.update(data,0,data.length);
    byte[] bytes=md.digest();
    return String.format("%0" + (bytes.length << 1) + "x",new BigInteger(1,bytes));
  }
 catch (  final NoSuchAlgorithmException e) {
    throw new UnsupportedOperationException(e);
  }
}
 

Example 3

From project adbcj, under directory /mysql/codec/src/main/java/org/adbcj/mysql/codec/.

Source file: PasswordEncryption.java

  18 
vote

public static byte[] encryptPassword(String password,byte[] salt) throws NoSuchAlgorithmException {
  MessageDigest md=MessageDigest.getInstance("SHA-1");
  byte[] hash1=md.digest(password.getBytes());
  md.reset();
  byte[] hash2=md.digest(hash1);
  md.reset();
  md.update(salt);
  md.update(hash2);
  byte[] digest=md.digest();
  for (int i=0; i < digest.length; i++) {
    digest[i]=(byte)(digest[i] ^ hash1[i]);
  }
  return digest;
}
 

Example 4

From project aether-core, under directory /aether-connector-asynchttpclient/src/test/java/org/eclipse/aether/connector/async/.

Source file: AsyncConnectorSuiteConfiguration.java

  18 
vote

private String digest(String string,String algo) throws NoSuchAlgorithmException, UnsupportedEncodingException {
  MessageDigest digest=MessageDigest.getInstance(algo);
  byte[] bytes=digest.digest(string.getBytes("UTF-8"));
  StringBuilder buffer=new StringBuilder(64);
  for (int i=0; i < bytes.length; i++) {
    int b=bytes[i] & 0xFF;
    if (b < 0x10) {
      buffer.append('0');
    }
    buffer.append(Integer.toHexString(b));
  }
  return buffer.toString();
}
 

Example 5

From project Alerte-voirie-android, under directory /src/com/fabernovel/alertevoirie/webservice/.

Source file: HttpPostRequest.java

  18 
vote

private static String sha1(String raw) throws UnsupportedEncodingException, NoSuchAlgorithmException {
  byte[] bytes=raw.getBytes("UTF-8");
  MessageDigest md=MessageDigest.getInstance(MGF1ParameterSpec.SHA1.getDigestAlgorithm());
  md.update(bytes);
  byte[] digest=md.digest();
  return toHex(digest);
}
 

Example 6

From project alfredo, under directory /alfredo/src/main/java/com/cloudera/alfredo/util/.

Source file: Signer.java

  18 
vote

/** 
 * Returns then signature of a string.
 * @param str string to sign.
 * @return the signature for the string.
 */
protected String computeSignature(String str){
  try {
    MessageDigest md=MessageDigest.getInstance("SHA");
    md.update(str.getBytes());
    md.update(secret);
    byte[] digest=md.digest();
    Base64 base64=new Base64(0);
    return base64.encodeToString(digest);
  }
 catch (  NoSuchAlgorithmException ex) {
    throw new RuntimeException("It should not happen, " + ex.getMessage(),ex);
  }
}
 

Example 7

From project amber, under directory /oauth-2.0/authzserver/src/main/java/org/apache/amber/oauth2/as/issuer/.

Source file: MD5Generator.java

  18 
vote

@Override public String generateValue(String param) throws OAuthSystemException {
  try {
    MessageDigest algorithm=MessageDigest.getInstance("MD5");
    algorithm.reset();
    algorithm.update(param.getBytes());
    byte[] messageDigest=algorithm.digest();
    return toHexString(messageDigest);
  }
 catch (  Exception e) {
    throw new OAuthSystemException("OAuth Token cannot be generated.",e);
  }
}
 

Example 8

From project AmDroid, under directory /AmDroid/src/main/java/com/jaeckel/amenoid/cwac/cache/.

Source file: SimpleWebImageCache.java

  18 
vote

static protected String md5(String s) throws Exception {
  MessageDigest md=MessageDigest.getInstance("MD5");
  md.update(s.getBytes());
  byte digest[]=md.digest();
  StringBuffer result=new StringBuffer();
  for (int i=0; i < digest.length; i++) {
    result.append(Integer.toHexString(0xFF & digest[i]));
  }
  return (result.toString());
}
 

Example 9

From project Amoeba-for-Aladdin, under directory /src/java/com/meidusa/amoeba/mysql/util/.

Source file: Security.java

  18 
vote

/** 
 * Stage one password hashing, used in MySQL 4.1 password handling
 * @param password plaintext password
 * @return stage one hash of password
 * @throws NoSuchAlgorithmException if the message digest 'SHA-1' is not available.
 */
static byte[] passwordHashStage1(String password) throws NoSuchAlgorithmException {
  MessageDigest md=MessageDigest.getInstance("SHA-1");
  StringBuffer cleansedPassword=new StringBuffer();
  int passwordLength=password.length();
  for (int i=0; i < passwordLength; i++) {
    char c=password.charAt(i);
    if ((c == ' ') || (c == '\t')) {
      continue;
    }
    cleansedPassword.append(c);
  }
  return md.digest(cleansedPassword.toString().getBytes());
}
 

Example 10

From project android-client_1, under directory /src/org/apache/qpid/management/common/sasl/.

Source file: UsernameHashedPasswordCallbackHandler.java

  18 
vote

public static char[] getHash(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
  byte[] data=text.getBytes("utf-8");
  MessageDigest md=MessageDigest.getInstance("MD5");
  for (  byte b : data) {
    md.update(b);
  }
  byte[] digest=md.digest();
  char[] hash=new char[digest.length];
  int index=0;
  for (  byte b : digest) {
    hash[index++]=(char)b;
  }
  return hash;
}
 

Example 11

From project Android-GifStitch, under directory /src/com/phunkosis/gifstitch/helpers/.

Source file: ShareHelper.java

  18 
vote

private static String generateSHA256(String offThis){
  String result="";
  try {
    MessageDigest md=MessageDigest.getInstance("SHA-256");
    md.update(offThis.getBytes());
    byte mdBytes[]=md.digest();
    result=bytesToHex(mdBytes);
  }
 catch (  NoSuchAlgorithmException e) {
    e.printStackTrace();
  }
  return result;
}
 

Example 12

From project android-rackspacecloud, under directory /src/com/rackspacecloud/android/.

Source file: PasswordManager.java

  18 
vote

private byte[] getHash(String password){
  MessageDigest m=null;
  try {
    m=MessageDigest.getInstance("SHA-256");
    m.update(password.getBytes());
  }
 catch (  NoSuchAlgorithmException e) {
    e.printStackTrace();
  }
catch (  NullPointerException e) {
    e.printStackTrace();
  }
  return m.digest();
}
 

Example 13

From project android-sdk, under directory /src/main/java/com/mobeelizer/mobile/android/.

Source file: MobeelizerInternalDatabase.java

  18 
vote

private String getMd5(final String password){
  MessageDigest m;
  try {
    m=MessageDigest.getInstance("MD5");
  }
 catch (  NoSuchAlgorithmException e) {
    throw new IllegalStateException(e.getMessage(),e);
  }
  m.update(password.getBytes(),0,password.length());
  String hash=new BigInteger(1,m.digest()).toString(16);
  return hash;
}
 

Example 14

From project androidquery, under directory /src/com/androidquery/util/.

Source file: AQUtility.java

  18 
vote

private static byte[] getMD5(byte[] data){
  MessageDigest digest;
  try {
    digest=java.security.MessageDigest.getInstance("MD5");
    digest.update(data);
    byte[] hash=digest.digest();
    return hash;
  }
 catch (  NoSuchAlgorithmException e) {
    AQUtility.report(e);
  }
  return null;
}
 

Example 15

From project Android_Pusher, under directory /src/de/roderick/weberknecht/.

Source file: WebSocketHandshake.java

  18 
vote

private byte[] md5(byte[] bytes){
  try {
    MessageDigest md=MessageDigest.getInstance("MD5");
    return md.digest(bytes);
  }
 catch (  NoSuchAlgorithmException e) {
    return null;
  }
}
 

Example 16

From project ANNIS, under directory /annis-gui/src/main/java/annis/security/.

Source file: Crypto.java

  18 
vote

/** 
 * Hashes a string using SHA-256. 
 */
public static String calculateSHAHash(String s) throws NoSuchAlgorithmException, UnsupportedEncodingException {
  MessageDigest md=MessageDigest.getInstance("SHA-256");
  md.update(s.getBytes("UTF-8"));
  byte[] digest=md.digest();
  StringBuilder sbHashVal=new StringBuilder();
  for (  byte b : digest) {
    sbHashVal.append(String.format("%02x",b));
  }
  return sbHashVal.toString();
}
 

Example 17

From project anode, under directory /app/src/org/meshpoint/anode/util/.

Source file: ModuleUtils.java

  18 
vote

public static String getResourceUriHash(String id){
  try {
    MessageDigest sha=MessageDigest.getInstance("SHA-1");
    sha.update(id.getBytes("iso-8859-1"));
    return digest2Hex(sha.digest());
  }
 catch (  Exception e) {
    return null;
  }
}
 

Example 18

From project any23, under directory /core/src/main/java/org/apache/any23/util/.

Source file: MathUtils.java

  18 
vote

public static final String md5(String s){
  try {
    MessageDigest md5=MessageDigest.getInstance("MD5");
    md5.reset();
    md5.update(s.getBytes());
    byte[] digest=md5.digest();
    StringBuffer result=new StringBuffer();
    for (    byte b : digest) {
      result.append(Integer.toHexString(0xFF & b));
    }
    return result.toString();
  }
 catch (  NoSuchAlgorithmException e) {
    throw new RuntimeException("Should never happen, MD5 is supported",e);
  }
}
 

Example 19

From project apps-for-android, under directory /Samples/Downloader/src/com/google/android/downloader/.

Source file: DownloaderActivity.java

  18 
vote

private MessageDigest createDigest() throws DownloaderException {
  MessageDigest digest;
  try {
    digest=MessageDigest.getInstance("MD5");
  }
 catch (  NoSuchAlgorithmException e) {
    throw new DownloaderException("Couldn't create MD5 digest");
  }
  return digest;
}
 

Example 20

From project Arecibo, under directory /aggregator/src/main/java/com/ning/arecibo/aggregator/dictionary/.

Source file: EventDictionary.java

  18 
vote

private String getInputEventSignature(SortedMap<String,Class> typeMap){
  try {
    MessageDigest md5=MessageDigest.getInstance("MD5");
    for (    SortedMap.Entry<String,Class> entry : typeMap.entrySet()) {
      md5.update(entry.getKey().getBytes());
      md5.update(entry.getValue().getSimpleName().getBytes());
    }
    byte[] d=md5.digest();
    return UUIDUtil.md5ToString(d);
  }
 catch (  NoSuchAlgorithmException e) {
    return null;
  }
}
 

Example 21

From project AsmackService, under directory /src/org/apache/qpid/management/common/sasl/.

Source file: UsernameHashedPasswordCallbackHandler.java

  18 
vote

public static char[] getHash(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
  byte[] data=text.getBytes("utf-8");
  MessageDigest md=MessageDigest.getInstance("MD5");
  for (  byte b : data) {
    md.update(b);
  }
  byte[] digest=md.digest();
  char[] hash=new char[digest.length];
  int index=0;
  for (  byte b : digest) {
    hash[index++]=(char)b;
  }
  return hash;
}
 

Example 22

From project ATHENA, under directory /core/web-resources/src/main/java/org/fracturedatlas/athena/web/filter/.

Source file: AthenaDigestAuthFilter.java

  18 
vote

/** 
 * Compute md5 hash of a string and returns the hexadecimal representation of it
 */
static String MD5(String text){
  try {
    MessageDigest md;
    md=MessageDigest.getInstance("MD5");
    md.update(text.getBytes("iso-8859-1"),0,text.length());
    byte[] md5hash=md.digest();
    String result=convertToHex(md5hash);
    return result;
  }
 catch (  Exception e) {
    throw new Error(e);
  }
}
 

Example 23

From project AuthDB, under directory /src/main/java/com/authdb/util/encryption/.

Source file: Encryption.java

  18 
vote

public static String md5(String data){
  try {
    byte[] bytes=data.getBytes("ISO-8859-1");
    MessageDigest md5er=MessageDigest.getInstance("MD5");
    byte[] hash=md5er.digest(bytes);
    return Util.bytes2hex(hash);
  }
 catch (  GeneralSecurityException e) {
    throw new RuntimeException(e);
  }
catch (  UnsupportedEncodingException e) {
    throw new RuntimeException(e);
  }
}
 

Example 24

From project authme-2.0, under directory /src/uk/org/whoami/authme/security/.

Source file: PasswordSecurity.java

  18 
vote

private static String getMD5(String message) throws NoSuchAlgorithmException {
  MessageDigest md5=MessageDigest.getInstance("MD5");
  md5.reset();
  md5.update(message.getBytes());
  byte[] digest=md5.digest();
  return String.format("%0" + (digest.length << 1) + "x",new BigInteger(1,digest));
}
 

Example 25

From project AuthMe-Reloaded, under directory /src/main/java/uk/org/whoami/authme/security/.

Source file: PasswordSecurity.java

  18 
vote

private static String getMD5(String message) throws NoSuchAlgorithmException {
  MessageDigest md5=MessageDigest.getInstance("MD5");
  md5.reset();
  md5.update(message.getBytes());
  byte[] digest=md5.digest();
  return String.format("%0" + (digest.length << 1) + "x",new BigInteger(1,digest));
}
 

Example 26

From project AuthMe-Reloaded-Charge-fix, under directory /src/uk/org/whoami/authme/security/.

Source file: PasswordSecurity.java

  18 
vote

private static String getMD5(String message) throws NoSuchAlgorithmException {
  MessageDigest md5=MessageDigest.getInstance("MD5");
  md5.reset();
  md5.update(message.getBytes());
  byte[] digest=md5.digest();
  return String.format("%0" + (digest.length << 1) + "x",new BigInteger(1,digest));
}
 

Example 27

From project avro, under directory /lang/java/avro/src/main/java/org/apache/avro/file/.

Source file: DataFileWriter.java

  18 
vote

private static byte[] generateSync(){
  try {
    MessageDigest digester=MessageDigest.getInstance("MD5");
    long time=System.currentTimeMillis();
    digester.update((UUID.randomUUID() + "@" + time).getBytes());
    return digester.digest();
  }
 catch (  NoSuchAlgorithmException e) {
    throw new RuntimeException(e);
  }
}
 

Example 28

From project Axon-trader, under directory /users/src/main/java/org/axonframework/samples/trader/users/util/.

Source file: DigestUtils.java

  18 
vote

/** 
 * Calculate the SHA1 hash for a given string.
 * @param text the given text to hash to a SHA1
 * @return the SHA1 Hash
 */
public static String sha1(String text){
  Assert.notNull(text);
  try {
    MessageDigest md=MessageDigest.getInstance("SHA1");
    return hex(md.digest(text.getBytes("UTF-8")));
  }
 catch (  NoSuchAlgorithmException ex) {
    throw new IllegalStateException("Unable to calculate hash. No SHA1 hasher available in this Java implementation",ex);
  }
catch (  UnsupportedEncodingException ex) {
    throw new IllegalStateException("Unable to calculate hash. UTF-8 encoding is not available in this Java implementation",ex);
  }
}
 

Example 29

From project azure-sdk-for-java-samples, under directory /WAAD.WebSSO.JAVA/java/code/libraries/waad-federation/src/main/java/com/microsoft/samples/federation/.

Source file: SamlTokenValidator.java

  18 
vote

private static String getThumbPrintFromCert(X509Certificate cert) throws NoSuchAlgorithmException, CertificateEncodingException {
  MessageDigest md=MessageDigest.getInstance("SHA-1");
  byte[] der=cert.getEncoded();
  md.update(der);
  byte[] digest=md.digest();
  return hexify(digest);
}
 

Example 30

From project BabelCraft-Legacy, under directory /src/main/java/com/craftfire/babelcraft/util/.

Source file: Encryption.java

  18 
vote

public String md5(String data){
  try {
    byte[] bytes=data.getBytes("ISO-8859-1");
    MessageDigest md5er=MessageDigest.getInstance("MD5");
    byte[] hash=md5er.digest(bytes);
    return util.bytes2hex(hash);
  }
 catch (  GeneralSecurityException e) {
    throw new RuntimeException(e);
  }
catch (  UnsupportedEncodingException e) {
    throw new RuntimeException(e);
  }
}
 

Example 31

From project backend-update-center2, under directory /src/main/java/org/jvnet/hudson/update_center/.

Source file: MavenArtifact.java

  18 
vote

/** 
 * Computes the SHA1 signature of the file.
 */
public String getDigest() throws IOException {
  try {
    MessageDigest sig=MessageDigest.getInstance("SHA1");
    FileInputStream fin=new FileInputStream(resolve());
    byte[] buf=new byte[2048];
    int len;
    while ((len=fin.read(buf,0,buf.length)) >= 0)     sig.update(buf,0,len);
    return new String(Base64.encodeBase64(sig.digest()));
  }
 catch (  NoSuchAlgorithmException e) {
    throw new IOException(e);
  }
}
 

Example 32

From project BazaarUtils, under directory /src/com/congenialmobile/utils/.

Source file: CodingUtils.java

  18 
vote

public static String byteArrayToSha1HexDigest(byte[] byteArray){
  try {
    MessageDigest hasher=MessageDigest.getInstance("SHA-1");
    hasher.update(byteArray);
    byte messageDigest[]=hasher.digest();
    StringBuilder hexString=new StringBuilder();
    for (int i=0; i < messageDigest.length; i++)     hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
    return hexString.toString();
  }
 catch (  NoSuchAlgorithmException e) {
    Log.w(TAG,"BazaarUtils :: CodingUtils :: byteArrayToSha1HexDigest",e);
    return null;
  }
}
 

Example 33

From project bbb-java, under directory /src/main/java/org/transdroid/util/.

Source file: FakeTrustManager.java

  18 
vote

private static String getThumbPrint(X509Certificate cert) throws NoSuchAlgorithmException, CertificateEncodingException {
  MessageDigest md=MessageDigest.getInstance("SHA-1");
  byte[] der=cert.getEncoded();
  md.update(der);
  byte[] digest=md.digest();
  return hexify(digest);
}
 

Example 34

From project BeeQueue, under directory /src/org/beequeue/hash/.

Source file: HashKey.java

  18 
vote

public static HashKey buildHashKey(HashKeyResource resource,InputStream in) throws IOException {
  byte[] buffer=BUFFER.get();
  if (buffer == null) {
    BUFFER.set(new byte[32 * 1024]);
    buffer=BUFFER.get();
  }
  MessageDigest md=MessageDigestUtils.md();
  int countRead;
  while ((countRead=in.read(buffer)) > 0) {
    md.update(buffer,0,countRead);
  }
  return new HashKey(resource,md.digest());
}
 

Example 35

From project bioclipse.speclipse, under directory /plugins/net.bioclipse.spectrum/src/spok/.

Source file: GenerateId.java

  18 
vote

/** 
 * Generates a unique identifier by generating a random number and getting its digest
 * @return the new SpectrumID
 */
public static String generateId(){
  try {
    SecureRandom prng=SecureRandom.getInstance("SHA1PRNG");
    String randomNum=new Integer(prng.nextInt()).toString();
    MessageDigest sha=MessageDigest.getInstance("SHA-1");
    byte[] result=sha.digest(randomNum.getBytes());
    spectrumID=hexEncode(result);
    spectrumID="sid_" + spectrumID;
  }
 catch (  NoSuchAlgorithmException ex) {
    System.err.println(ex);
  }
  return spectrumID;
}
 

Example 36

From project bookmarktodesktop-android-application, under directory /src/be/vbsteven/bmtodesk/.

Source file: MD5.java

  18 
vote

public static byte[] md5Bytes(String s){
  try {
    MessageDigest digest=java.security.MessageDigest.getInstance("MD5");
    digest.update(s.getBytes());
    byte passDigest[]=digest.digest();
    return passDigest;
  }
 catch (  NoSuchAlgorithmException e) {
  }
  return null;
}
 

Example 37

From project brix-cms, under directory /brix-rmiserver/src/main/java/org/brixcms/rmiserver/.

Source file: PasswordEncoder.java

  18 
vote

/** 
 * Creates the hash of the password and concatenated salt
 * @param password password string
 * @param salt     salt string
 * @return SHA1 hash of concatenated password and salt
 */
private String hash(String password,String salt){
  String saltedPassword=salt + password;
  MessageDigest sha1;
  try {
    sha1=MessageDigest.getInstance("SHA1");
    sha1.update(saltedPassword.getBytes());
    byte[] saltedHash=sha1.digest();
    return bytesToHexString(saltedHash);
  }
 catch (  NoSuchAlgorithmException e) {
    throw new NestableRuntimeException(e);
  }
}
 

Example 38

From project BSPAN---Bluetooth-Sensor-Processing-for-Android, under directory /AndroidSpineServer/src/com/t2/.

Source file: SharedPref.java

  18 
vote

private static String md5(String s){
  MessageDigest m=null;
  try {
    m=java.security.MessageDigest.getInstance("MD5");
  }
 catch (  NoSuchAlgorithmException e) {
  }
  if (m != null)   m.update(s.getBytes(),0,s.length());
  String hash=new BigInteger(1,m.digest()).toString();
  return hash;
}
 

Example 39

From project cas, under directory /cas-server-core/src/main/java/org/jasig/cas/authentication/principal/.

Source file: ShibbolethCompatiblePersistentIdGenerator.java

  18 
vote

public String generate(final Principal principal,final Service service){
  try {
    final MessageDigest md=MessageDigest.getInstance("SHA");
    md.update(service.getId().getBytes());
    md.update(CONST_SEPARATOR);
    md.update(principal.getId().getBytes());
    md.update(CONST_SEPARATOR);
    return Base64.encodeBase64String(md.digest(this.salt)).replaceAll(System.getProperty("line.separator"),"");
  }
 catch (  final NoSuchAlgorithmException e) {
    throw new RuntimeException(e);
  }
}
 

Example 40

From project Catroid-maven-playground, under directory /src/main/java/at/tugraz/ist/catroid/utils/.

Source file: Utils.java

  18 
vote

private static MessageDigest getMD5MessageDigest(){
  MessageDigest messageDigest=null;
  try {
    messageDigest=MessageDigest.getInstance("MD5");
  }
 catch (  NoSuchAlgorithmException e) {
    Log.w(TAG,"NoSuchAlgorithmException thrown in getMD5MessageDigest()");
  }
  return messageDigest;
}
 

Example 41

From project chililog-server, under directory /src/main/java/org/chililog/server/common/.

Source file: CryptoUtils.java

  18 
vote

/** 
 * MD5 hash
 * @param s string to hash
 * @return MD5 hash as a hex string
 * @throws ChiliLogException
 */
public static String createMD5Hash(String s) throws ChiliLogException {
  try {
    MessageDigest md=MessageDigest.getInstance("MD5");
    byte[] array=md.digest(s.getBytes("CP1252"));
    StringBuffer sb=new StringBuffer();
    for (int i=0; i < array.length; ++i) {
      sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3));
    }
    return sb.toString();
  }
 catch (  Exception ex) {
    throw new ChiliLogException(ex,"Error attempting to MD5 hash: " + ex.getMessage());
  }
}
 

Example 42

From project cloudbees-api-client, under directory /cloudbees-api-client/src/main/java/com/cloudbees/upload/.

Source file: JarUtils.java

  18 
vote

private static String sha256(InputStream data) throws IOException {
  MessageDigest digest=getDigest("SHA-256");
  byte[] buffer=new byte[STREAM_BUFFER_LENGTH];
  int read=data.read(buffer,0,STREAM_BUFFER_LENGTH);
  while (read > -1) {
    digest.update(buffer,0,read);
    read=data.read(buffer,0,STREAM_BUFFER_LENGTH);
  }
  return asHex(digest.digest());
}
 

Example 43

From project CMM-data-grabber, under directory /paul/src/main/java/au/edu/uq/cmm/paul/grabber/.

Source file: HashUtils.java

  18 
vote

public static String fileHash(File source) throws FileNotFoundException, IOException {
  try (FileInputStream fis=new FileInputStream(source)){
    MessageDigest md=HashUtils.createDigester();
    byte[] data=new byte[8192];
    int count;
    while ((count=fis.read(data)) > 0) {
      md.update(data,0,count);
    }
    byte[] hash=md.digest();
    return HashUtils.bytesToHexString(hash);
  }
 }
 

Example 44

From project code_swarm, under directory /src/.

Source file: AvatarFetcher.java

  18 
vote

protected static String md5Hex(String message){
  try {
    MessageDigest md=MessageDigest.getInstance("MD5");
    return hex(md.digest(message.getBytes("CP1252")));
  }
 catch (  NoSuchAlgorithmException e) {
  }
catch (  UnsupportedEncodingException e) {
  }
  return null;
}
 

Example 45

From project code_swarm-gource-my-conf, under directory /src/.

Source file: AvatarFetcher.java

  18 
vote

protected static String md5Hex(String message){
  try {
    MessageDigest md=MessageDigest.getInstance("MD5");
    return hex(md.digest(message.getBytes("CP1252")));
  }
 catch (  NoSuchAlgorithmException e) {
  }
catch (  UnsupportedEncodingException e) {
  }
  return null;
}
 

Example 46

From project cogroo4, under directory /lang/pt_br/cogroo-addon/src/org/cogroo/addon/util/.

Source file: SecurityUtil.java

  18 
vote

/** 
 * Encrypt a string using SHA
 * @param plaintext the original text
 * @return resultant hash
 */
public synchronized String encrypt(String plaintext){
  MessageDigest md=null;
  try {
    md=MessageDigest.getInstance("SHA");
    md.update(plaintext.getBytes(UTF8));
  }
 catch (  Exception e) {
    LOG.log(Level.SEVERE,"Should not happen!",e);
  }
  byte raw[]=md.digest();
  return encode(raw);
}
 

Example 47

From project cometd, under directory /cometd-java/cometd-java-oort/src/main/java/org/cometd/oort/.

Source file: Oort.java

  18 
vote

protected String encodeSecret(String secret){
  try {
    MessageDigest digest=MessageDigest.getInstance("SHA-1");
    return new String(B64Code.encode(digest.digest(secret.getBytes("UTF-8"))));
  }
 catch (  Exception x) {
    throw new IllegalArgumentException(x);
  }
}
 

Example 48

From project CommitCoin, under directory /src/com/google/bitcoin/core/.

Source file: Sha256Hash.java

  18 
vote

/** 
 * Calculates the (one-time) hash of contents and returns it as a new wrapped hash.
 */
public static Sha256Hash create(byte[] contents){
  try {
    MessageDigest digest=MessageDigest.getInstance("SHA-256");
    return new Sha256Hash(digest.digest(contents));
  }
 catch (  NoSuchAlgorithmException e) {
    throw new RuntimeException(e);
  }
}
 

Example 49

From project core_3, under directory /src/main/java/org/animotron/graph/builder/.

Source file: FastGraphBuilder.java

  18 
vote

@Override protected byte[] end(Object[] o,boolean hasChild){
  MessageDigest md=(MessageDigest)o[0];
  if (!(Boolean)o[7]) {
    updateMD(md,(Statement)o[1]);
  }
  o[8]=hash=md.digest();
  return hash;
}
 

Example 50

From project AceWiki, under directory /src/ch/uzh/ifi/attempto/acewiki/core/.

Source file: User.java

  17 
vote

/** 
 * Returns a hash value for a given plain-text password using the SHA-256 algorithm.
 * @param password The plain-text password for which a hash value should be created.
 * @return The hash value.
 */
public static String getPasswordHash(String password){
  try {
    MessageDigest md=MessageDigest.getInstance("SHA-256");
    md.update(password.getBytes());
    byte[] byteData=md.digest();
    StringBuffer sb=new StringBuffer();
    for (int i=0; i < byteData.length; i++) {
      sb.append(Integer.toString((byteData[i] & 0xff) + 0x100,16).substring(1));
    }
    return sb.toString();
  }
 catch (  Exception ex) {
    ex.printStackTrace();
    return null;
  }
}
 

Example 51

From project amplafi-sworddance, under directory /src/main/java/com/sworddance/util/.

Source file: RandomGUID.java

  17 
vote

private void getRandomGUID(boolean secure){
  MessageDigest messageHash;
  StringBuilder sbValueBeforeHash=new StringBuilder();
  try {
    messageHash=MessageDigest.getInstance("SHA-1");
  }
 catch (  NoSuchAlgorithmException e) {
    throw new ApplicationIllegalArgumentException(e);
  }
  long time=System.nanoTime();
  long rand=0;
  if (secure) {
    rand=MySecureRand.nextLong();
  }
 else {
    rand=MyRand.nextLong();
  }
  sbValueBeforeHash.append(SId);
  sbValueBeforeHash.append(":");
  sbValueBeforeHash.append(Long.toString(time));
  sbValueBeforeHash.append(":");
  sbValueBeforeHash.append(Long.toString(rand));
  valueBeforeHash=sbValueBeforeHash.toString();
  messageHash.update(valueBeforeHash.getBytes());
  byte[] array=messageHash.digest();
  StringBuffer sb=new StringBuffer();
  for (int j=0; j < array.length; ++j) {
    int b=array[j] & 0xFF;
    if (b < 0x10) {
      sb.append('0');
    }
    sb.append(Integer.toHexString(b));
  }
  valueAfterHash=sb.toString();
}
 

Example 52

From project android-bankdroid, under directory /src/com/liato/bankdroid/lockpattern/.

Source file: LockPatternUtils.java

  17 
vote

static byte[] patternToHash(List<LockPatternView.Cell> pattern){
  if (pattern == null) {
    return null;
  }
  final int patternSize=pattern.size();
  byte[] res=new byte[patternSize];
  for (int i=0; i < patternSize; i++) {
    LockPatternView.Cell cell=pattern.get(i);
    res[i]=(byte)(cell.getRow() * 3 + cell.getColumn());
  }
  try {
    MessageDigest md=MessageDigest.getInstance("SHA-1");
    byte[] hash=md.digest(res);
    return hash;
  }
 catch (  NoSuchAlgorithmException nsa) {
    return res;
  }
}
 

Example 53

From project android_5, under directory /src/aarddict/.

Source file: Volume.java

  17 
vote

public void verify(VerifyProgressListener listener) throws IOException, NoSuchAlgorithmException {
  FileInputStream fis=new FileInputStream(origFile);
  fis.skip(44);
  byte[] buff=new byte[1 << 16];
  MessageDigest m=MessageDigest.getInstance("SHA-1");
  int readCount;
  long totalReadCount=0;
  double totalBytes=origFile.length() - 44;
  boolean proceed=true;
  while ((readCount=fis.read(buff)) != -1) {
    m.update(buff,0,readCount);
    totalReadCount+=readCount;
    proceed=listener.updateProgress(this,totalReadCount / totalBytes);
  }
  fis.close();
  if (proceed) {
    BigInteger b=new BigInteger(1,m.digest());
    String calculated=b.toString(16);
    Log.d(TAG,"calculated: " + calculated + " actual: "+ sha1sum);
    listener.verified(this,calculated.equals(this.sha1sum));
  }
}
 

Example 54

From project android_build, under directory /tools/signapk/.

Source file: SignApk.java

  17 
vote

/** 
 * Add the SHA1 of every file to the manifest, creating it if necessary. 
 */
private static Manifest addDigestsToManifest(JarFile jar) throws IOException, GeneralSecurityException {
  Manifest input=jar.getManifest();
  Manifest output=new Manifest();
  Attributes main=output.getMainAttributes();
  if (input != null) {
    main.putAll(input.getMainAttributes());
  }
 else {
    main.putValue("Manifest-Version","1.0");
    main.putValue("Created-By","1.0 (Android SignApk)");
  }
  BASE64Encoder base64=new BASE64Encoder();
  MessageDigest md=MessageDigest.getInstance("SHA1");
  byte[] buffer=new byte[4096];
  int num;
  TreeMap<String,JarEntry> byName=new TreeMap<String,JarEntry>();
  for (Enumeration<JarEntry> e=jar.entries(); e.hasMoreElements(); ) {
    JarEntry entry=e.nextElement();
    byName.put(entry.getName(),entry);
  }
  for (  JarEntry entry : byName.values()) {
    String name=entry.getName();
    if (!entry.isDirectory() && !name.equals(JarFile.MANIFEST_NAME) && !name.equals(CERT_SF_NAME)&& !name.equals(CERT_RSA_NAME)&& (stripPattern == null || !stripPattern.matcher(name).matches())) {
      InputStream data=jar.getInputStream(entry);
      while ((num=data.read(buffer)) > 0) {
        md.update(buffer,0,num);
      }
      Attributes attr=null;
      if (input != null)       attr=input.getAttributes(name);
      attr=attr != null ? new Attributes(attr) : new Attributes();
      attr.putValue("SHA1-Digest",base64.encode(md.digest()));
      output.getEntries().put(name,attr);
    }
  }
  return output;
}
 

Example 55

From project android_packages_apps_Superuser, under directory /src/com/noshufou/android/su/util/.

Source file: Util.java

  17 
vote

public static String getHash(String pin){
  MessageDigest digest;
  try {
    digest=MessageDigest.getInstance("SHA-1");
  }
 catch (  NoSuchAlgorithmException e) {
    Log.e("Utils","NoSuchAlgorithm, storing in plain text...",e);
    return pin;
  }
  digest.reset();
  try {
    byte[] input=digest.digest(pin.getBytes("UTF-8"));
    String base64=Base64.encode(input);
    return base64;
  }
 catch (  UnsupportedEncodingException e) {
    Log.e("Utils","UnsupportedEncoding, storing in plain text...",e);
    return pin;
  }
}
 

Example 56

From project androvoip, under directory /src/com/mexuar/corraleta/protocol/.

Source file: ProtocolControlFrame.java

  17 
vote

/** 
 * Builds authentication IE. This method is called by sendAuthRep and sendRegReq.
 * @param iep The original IE
 * @param nip The new IE
 * @param pass The password
 * @see #sendAuthRep
 * @see #sendRegReq
 */
private void buildAuthInfoElements(InfoElement iep,InfoElement nip,String pass){
  nip.username=iep.username;
  nip.refresh=nip.refresh;
  if (_iep.authmethods != null) {
    int model=iep.authmethods.intValue();
    if ((model & 2) > 0) {
      try {
        final MessageDigest digest=MessageDigest.getInstance("MD5");
        digest.update(_iep.challenge.getBytes());
        digest.update(pass.getBytes());
        nip.md5Result=Binder.enHex(digest.digest(),null);
      }
 catch (      NoSuchAlgorithmException e) {
        android.util.Log.e("IAX2","MD5 not supported.");
        e.printStackTrace();
      }
    }
 else     if ((model & 1) > 0) {
      nip.md5Result=pass;
    }
  }
}
 

Example 57

From project ardverk-dht, under directory /components/store/src/main/java/org/ardverk/dht/storage/.

Source file: IndexDatastore.java

  17 
vote

@Override protected Response handlePut(Contact src,Key key,Request request,InputStream in) throws IOException {
  Context context=request.getContext();
  MessageDigest md5=MessageDigestUtils.createMD5();
  MessageDigest sha1=MessageDigestUtils.createSHA1();
  DigestInputStream dis=new DigestInputStream(in,MessageDigestUtils.wrap(md5,sha1));
  KUID valueId=KUID.createRandom(key.getId());
  File contentFile=null;
  boolean success=false;
  try {
    contentFile=mkContentFile(key,valueId,true);
    writeContent(context,contentFile,dis);
    if (!digest(context,Constants.CONTENT_MD5,md5)) {
      return ResponseFactory.INTERNAL_SERVER_ERROR;
    }
    if (!digest(context,Constants.CONTENT_SHA1,sha1)) {
      return ResponseFactory.INTERNAL_SERVER_ERROR;
    }
    context.addHeader(Constants.VALUE_ID,valueId.toHexString());
    upsertVclock(key,context);
    try {
      index.add(key,context,valueId);
    }
 catch (    Exception err) {
      throw new IOException("Exception",err);
    }
    success=true;
    return ResponseFactory.ok();
  }
  finally {
    if (!success) {
      deleteAll(contentFile);
    }
  }
}
 

Example 58

From project arquillian-graphene, under directory /graphene-selenium/graphene-selenium-impl/src/main/java/org/jboss/arquillian/ajocado/utils/.

Source file: URLUtils.java

  17 
vote

/** 
 * Gets a MD5 digest of some resource obtains as input stream from connection to URL given by URL string.
 * @param url of the resource
 * @return MD5 message digest of resource
 * @throws IOException when connection to URL fails
 */
public static String resourceMd5Digest(String url) throws IOException {
  URLConnection connection=new URL(url).openConnection();
  InputStream in=connection.getInputStream();
  MessageDigest digest;
  try {
    digest=MessageDigest.getInstance("MD5");
  }
 catch (  NoSuchAlgorithmException ex) {
    throw new IllegalStateException("MD5 hashing is unsupported",ex);
  }
  byte[] buffer=new byte[MD5_BUFFER_SIZE];
  int read=0;
  while ((read=in.read(buffer)) > 0) {
    digest.update(buffer,0,read);
  }
  byte[] md5sum=digest.digest();
  BigInteger bigInt=new BigInteger(1,md5sum);
  return bigInt.toString(HEX_RADIX);
}
 

Example 59

From project beintoo-android-sdk, under directory /BeintooSDK/src/com/beintoo/beintoosdkutility/.

Source file: DeviceId.java

  17 
vote

public static String toSHA1(String input){
  try {
    int lenght=40;
    MessageDigest sha=MessageDigest.getInstance("SHA-1");
    byte[] messageDigest=sha.digest(input.getBytes());
    BigInteger number=new BigInteger(1,messageDigest);
    String out=number.toString(16);
    if (out.length() < lenght) {
      char[] charArray=new char[lenght];
      Arrays.fill(charArray,'0');
      out.getChars(0,out.length(),charArray,lenght - out.length());
      out=new String(charArray);
    }
    return out;
  }
 catch (  Exception ex) {
    ex.printStackTrace();
  }
  return null;
}
 

Example 60

From project BF3-Battlelog, under directory /src/com/ninetwozero/battlelog/http/.

Source file: RequestHandler.java

  17 
vote

/** 
 * @author http://androidgenuine.com/?p=402
 */
public String hash(String str){
  try {
    MessageDigest digest=MessageDigest.getInstance("SHA-256");
    digest.update(str.getBytes());
    byte messageDigest[]=digest.digest();
    StringBuffer hexString=new StringBuffer();
    for (int i=0; i < messageDigest.length; i++) {
      String h=Integer.toHexString(0xFF & messageDigest[i]);
      while (h.length() < 2) {
        h="0" + h;
      }
      hexString.append(h);
    }
    return hexString.toString();
  }
 catch (  NoSuchAlgorithmException e) {
    e.printStackTrace();
  }
  return "";
}
 

Example 61

From project BombusLime, under directory /src/org/bombusim/lime/data/.

Source file: Vcard.java

  17 
vote

private void decodeAvatar(){
  int sz=Lime.getInstance().avatarSize;
  int szt=sz * 2;
  byte[] photobin=Base64.decode(base64Photo,Base64.DEFAULT);
  Bitmap avatarTmp=decodeBitmap(szt,photobin);
  int h=avatarTmp.getHeight();
  int w=avatarTmp.getWidth();
  if (h == 0 || w == 0) {
    photoHash=AVATAR_MISSING;
    return;
  }
  if (h > w) {
    w=(w * sz) / h;
    h=sz;
  }
 else {
    h=(h * sz) / w;
    w=sz;
  }
  Bitmap scaled=Bitmap.createScaledBitmap(avatarTmp,w,h,true);
  avatarTmp.recycle();
  if (h == w) {
    avatar=scaled;
  }
 else {
    avatar=Bitmap.createBitmap(sz,sz,Bitmap.Config.ARGB_8888);
    Canvas c=new Canvas(avatar);
    c.drawColor(Color.DKGRAY);
    c.drawBitmap(scaled,(sz - w) / 2,(sz - h) / 2,null);
  }
  try {
    MessageDigest sha1=MessageDigest.getInstance("SHA-1");
    photoHash=strconv.byteArrayToHexString(sha1.digest(photobin));
    LimeLog.d("Img SHA-1",jid,photoHash);
  }
 catch (  NoSuchAlgorithmException e) {
    photoHash=AVATAR_MISSING;
  }
}
 

Example 62

From project brut.apktool.smali, under directory /dexlib/src/main/java/org/jf/dexlib/.

Source file: DexFile.java

  17 
vote

/** 
 * Calculates the signature for the dex file in the given byte array, and then writes the signature to the appropriate location in the header containing in the array
 * @param bytes non-null; the bytes of the file
 */
public static void calcSignature(byte[] bytes){
  MessageDigest md;
  try {
    md=MessageDigest.getInstance("SHA-1");
  }
 catch (  NoSuchAlgorithmException ex) {
    throw new RuntimeException(ex);
  }
  md.update(bytes,32,bytes.length - 32);
  try {
    int amt=md.digest(bytes,12,20);
    if (amt != 20) {
      throw new RuntimeException("unexpected digest write: " + amt + " bytes");
    }
  }
 catch (  DigestException ex) {
    throw new RuntimeException(ex);
  }
}
 

Example 63

From project build-info, under directory /build-info-api/src/test/java/org/jfrog/build/api/.

Source file: FileChecksumCalculatorTest.java

  17 
vote

/** 
 * Returns the checksum of the given file
 * @param algorithm  Algorithm to calculate by
 * @param fileToRead File to calculate
 * @return Checksum value
 * @throws NoSuchAlgorithmException Thrown if MD5 or SHA1 aren't supported
 * @throws IOException              Thrown if any error occurs while reading the file or calculating the checksum
 */
private String getChecksum(String algorithm,File fileToRead) throws NoSuchAlgorithmException, IOException {
  MessageDigest digest=MessageDigest.getInstance(algorithm);
  FileInputStream inputStream=new FileInputStream(fileToRead);
  byte[] buffer=new byte[32768];
  try {
    int size=inputStream.read(buffer,0,32768);
    while (size >= 0) {
      digest.update(buffer,0,size);
      size=inputStream.read(buffer,0,32768);
    }
  }
  finally {
    if (inputStream != null) {
      inputStream.close();
    }
  }
  byte[] bytes=digest.digest();
  if (bytes.length != 16 && bytes.length != 20) {
    int bitLength=bytes.length * 8;
    throw new IllegalArgumentException("Unrecognised length for binary data: " + bitLength + " bits");
  }
  StringBuilder sb=new StringBuilder();
  for (  byte aBinaryData : bytes) {
    String t=Integer.toHexString(aBinaryData & 0xff);
    if (t.length() == 1) {
      sb.append("0");
    }
    sb.append(t);
  }
  return sb.toString().trim();
}
 

Example 64

From project candlepin, under directory /src/main/java/org/candlepin/util/.

Source file: Util.java

  17 
vote

public static String hash(String password){
  String salt="b669e3274a43f20769d3dedf03e9ac180e160f92";
  String combined=salt + password;
  MessageDigest md;
  try {
    md=MessageDigest.getInstance("SHA-1");
  }
 catch (  NoSuchAlgorithmException nsae) {
    throw new RuntimeException(nsae);
  }
  try {
    md.update(combined.getBytes("UTF-8"),0,combined.length());
  }
 catch (  UnsupportedEncodingException uee) {
    throw new RuntimeException(uee);
  }
  byte[] sha1hash=md.digest();
  return new String(Hex.encodeHex(sha1hash));
}
 

Example 65

From project capedwarf-green, under directory /server-api/src/main/java/org/jboss/capedwarf/server/api/security/impl/.

Source file: BasicSecurityProvider.java

  17 
vote

public String hash(String... strings){
  if (strings == null || strings.length == 0)   throw new IllegalArgumentException("Null or empty strings: " + Arrays.toString(strings));
  try {
    MessageDigest m=MessageDigest.getInstance("MD5");
    StringBuilder builder=new StringBuilder();
    for (    String s : strings)     builder.append(s);
    builder.append(SALT);
    byte[] bytes=builder.toString().getBytes();
    m.update(bytes,0,bytes.length);
    BigInteger i=new BigInteger(1,m.digest());
    return String.format("%1$032X",i);
  }
 catch (  NoSuchAlgorithmException e) {
    throw new IllegalArgumentException(e);
  }
}
 

Example 66

From project Carolina-Digital-Repository, under directory /djatoka-cdr/src/gov/lanl/adore/djatoka/openurl/.

Source file: OpenURLJP2KService.java

  17 
vote

private static final String getTileHash(ImageRecord r,DjatokaDecodeParam params) throws Exception {
  String id=r.getIdentifier();
  int level=params.getLevel();
  String region=params.getRegion();
  int rotateDegree=params.getRotationDegree();
  double scalingFactor=params.getScalingFactor();
  int[] scalingDims=params.getScalingDimensions();
  String scale="";
  if (scalingDims != null && scalingDims.length == 1)   scale=scalingDims[0] + "";
  if (scalingDims != null && scalingDims.length == 2)   scale=scalingDims[0] + "," + scalingDims[1];
  int clayer=params.getCompositingLayer();
  String rft_id=id + "|" + level+ "|"+ region+ "|"+ rotateDegree+ "|"+ scalingFactor+ "|"+ scale+ "|"+ clayer;
  MessageDigest complete=MessageDigest.getInstance("SHA1");
  return new String(complete.digest(rft_id.getBytes()));
}
 

Example 67

From project caseconductor-platform, under directory /utest-common/src/main/java/com/utest/util/.

Source file: EncodeUtil.java

  17 
vote

public static String encode(final String plaintext){
  try {
    final byte[] plain=plaintext.getBytes();
    byte[] hashed;
    final MessageDigest sha=MessageDigest.getInstance(ALGORITHM);
    sha.update(plain);
    hashed=sha.digest();
    final StringBuffer sb=new StringBuffer();
    final int length=hashed.length;
    for (int i=0; i < (length) && i < hashed.length; i++) {
      sb.append(Character.forDigit((hashed[i] >>> 4) & 0xf,16));
      sb.append(Character.forDigit(hashed[i] & 0xf,16));
    }
    return sb.toString();
  }
 catch (  final NoSuchAlgorithmException e) {
    throw new RuntimeException(e);
  }
}
 

Example 68

From project ceylon-module-resolver, under directory /impl/src/main/java/com/redhat/ceylon/cmr/impl/.

Source file: IOUtils.java

  17 
vote

static String sha1(InputStream is){
  final MessageDigest digest;
  try {
    digest=MessageDigest.getInstance("SHA-1");
  }
 catch (  NoSuchAlgorithmException e) {
    log.warning("Failed to get a SHA-1 message digest, your JRE does not follow the specs. No SHA-1 signature will be made");
    return null;
  }
  final byte[] buffer=new byte[1024];
  int read;
  try {
    while ((read=is.read(buffer)) != -1) {
      digest.update(buffer,0,read);
    }
  }
 catch (  IOException e) {
    log.warning("Failed to read input stream, no SHA-1 signature will be made");
    return null;
  }
 finally {
    safeClose(is);
  }
  return toHexString(digest.digest());
}
 

Example 69

From project ChkBugReport, under directory /src/com/sonyericsson/chkbugreport/.

Source file: Util.java

  17 
vote

public static String calcMD5(InputStream is){
  try {
    MessageDigest md=MessageDigest.getInstance("MD5");
    byte buff[]=new byte[0x10000];
    while (true) {
      int read=is.read(buff);
      if (read <= 0)       break;
      md.update(buff,0,read);
    }
    StringBuffer sb=new StringBuffer();
    byte[] hash=md.digest();
    for (    byte b : hash) {
      sb.append(Integer.toHexString((b >> 4) & 0xf));
      sb.append(Integer.toHexString((b >> 0) & 0xf));
    }
    return sb.toString();
  }
 catch (  Exception e) {
    e.printStackTrace();
    return null;
  }
}
 

Example 70

From project chukwa, under directory /src/main/java/org/apache/hadoop/chukwa/datacollection/collector/servlet/.

Source file: LogDisplayServlet.java

  17 
vote

private String getSID(Chunk c){
  try {
    MessageDigest md;
    md=MessageDigest.getInstance("MD5");
    md.update(c.getSource().getBytes());
    md.update(c.getStreamName().getBytes());
    md.update(c.getTags().getBytes());
    StringBuilder sb=new StringBuilder();
    byte[] bytes=md.digest();
    for (int i=0; i < bytes.length; ++i) {
      if ((bytes[i] & 0xF0) == 0)       sb.append('0');
      sb.append(Integer.toHexString(0xFF & bytes[i]));
    }
    return sb.toString();
  }
 catch (  NoSuchAlgorithmException n) {
    log.fatal(n);
    System.exit(0);
    return null;
  }
}
 

Example 71

From project Clotho-Core, under directory /ClothoProject/ClothoCore/src/org/clothocore/api/data/.

Source file: ObjBase.java

  17 
vote

/** 
 * Converts a String into a Hash string
 * @param uuidToHash
 * @return
 */
public static String generateUUIDAsHash(String uuidToHash){
  byte[] defaultBytes=uuidToHash.getBytes();
  try {
    MessageDigest algorithm=MessageDigest.getInstance("MD5");
    algorithm.reset();
    algorithm.update(defaultBytes);
    byte messageDigest[]=algorithm.digest();
    StringBuffer hexString=new StringBuffer();
    for (int i=0; i < messageDigest.length; i++) {
      hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
    }
    String out="";
    out=hexString.toString();
    return out;
  }
 catch (  NoSuchAlgorithmException nsae) {
  }
  return "";
}
 

Example 72

From project clutter, under directory /src/clutter/hypertoolkit/security/.

Source file: Hash.java

  17 
vote

public SaltedSum(String salt,String input){
  try {
    StringBuilder sb=new StringBuilder();
    sb.append(salt);
    sb.append(StringUtils.defaultString(input));
    MessageDigest digest=MessageDigest.getInstance("SHA1");
    digest.update(sb.toString().getBytes("UTF-8"));
    byte[] hash=digest.digest();
    StringBuilder output=new StringBuilder();
    output.append(salt);
    output.append(new String(Base64.encodeBase64(hash)));
    result=output.toString();
  }
 catch (  Exception e) {
    Log.fatal(this,"WTF - This JVM cannot do SHA1 or UTF8 or base64???",e);
    throw new RuntimeException(e);
  }
}
 

Example 73

From project connectbot, under directory /src/sk/vx/connectbot/util/.

Source file: Encryptor.java

  17 
vote

/** 
 * Encrypt the specified cleartext using the given password. With the correct salt, number of iterations, and password, the decrypt() method reverses the effect of this method. This method generates and uses a random salt, and the user-specified number of iterations and password to create a 16-byte secret key and 16-byte initialization vector. The secret key and initialization vector are then used in the AES-128 cipher to encrypt the given cleartext.
 * @param salt salt that was used in the encryption (to be populated)
 * @param iterations number of iterations to use in salting
 * @param password password to be used for encryption
 * @param cleartext cleartext to be encrypted
 * @return ciphertext
 * @throws Exception on any error encountered in encryption
 */
public static byte[] encrypt(final byte[] salt,final int iterations,final String password,final byte[] cleartext) throws Exception {
  SecureRandom.getInstance(RNG_ALGORITHM).nextBytes(salt);
  final MessageDigest shaDigest=MessageDigest.getInstance(DIGEST_ALGORITHM);
  byte[] pw=password.getBytes(CHARSET_NAME);
  for (int i=0; i < iterations; i++) {
    final byte[] salted=new byte[pw.length + salt.length];
    System.arraycopy(pw,0,salted,0,pw.length);
    System.arraycopy(salt,0,salted,pw.length,salt.length);
    Arrays.fill(pw,(byte)0x00);
    shaDigest.reset();
    pw=shaDigest.digest(salted);
    Arrays.fill(salted,(byte)0x00);
  }
  final byte[] key=new byte[16];
  final byte[] iv=new byte[16];
  System.arraycopy(pw,0,key,0,16);
  System.arraycopy(pw,16,iv,0,16);
  Arrays.fill(pw,(byte)0x00);
  final Cipher cipher=Cipher.getInstance(CIPHER_ALGORITHM);
  cipher.init(Cipher.ENCRYPT_MODE,new SecretKeySpec(key,KEY_ALGORITHM),new IvParameterSpec(iv));
  Arrays.fill(key,(byte)0x00);
  Arrays.fill(iv,(byte)0x00);
  return cipher.doFinal(cleartext);
}
 

Example 74

From project Core_2, under directory /shell/src/main/java/org/jboss/forge/shell/plugins/builtin/.

Source file: FingerprintPlugin.java

  17 
vote

@DefaultCommand public void run(@PipeIn final InputStream pipeIn,@Option(name="cipher",help="hash cipher to use (default: 'SHA-256')",defaultValue="SHA-256") String cipher,@Option(description="FILE ...",defaultValue="*") Resource<?>[] resources,final PipeOut pipeOut) throws IOException {
  cipher=cipher.toUpperCase().trim();
  String name=null;
  try {
    final MessageDigest md=MessageDigest.getInstance(cipher);
    if (pipeIn != null) {
      name="<pipe>";
      fingerprint(pipeIn,md);
    }
 else     if (resources != null) {
      InputStream inputStream=null;
      StringBuilder names=new StringBuilder();
      for (      Resource<?> r : resources) {
        if (r.isFlagSet(ResourceFlag.Node))         continue;
        names.append(r.getName()).append(" ");
        try {
          fingerprint(inputStream=r.getResourceInputStream(),md);
        }
  finally {
          if (inputStream != null)           inputStream.close();
        }
      }
      name=names.toString().trim();
    }
    if (pipeOut.isPiped()) {
      name="";
    }
    pipeOut.print(name);
    pipeOut.print(" ");
    for (    byte b : md.digest()) {
      pipeOut.print(Integer.toHexString(0xFF & b));
    }
    pipeOut.println();
  }
 catch (  NoSuchAlgorithmException e) {
    throw new RuntimeException("the hashing algorithm '" + cipher + "' could not be found");
  }
}
 

Example 75

From project agit, under directory /agit/src/main/java/com/madgag/agit/util/.

Source file: DigestUtils.java

  15 
vote

static MessageDigest getDigest(String algorithm){
  try {
    return MessageDigest.getInstance(algorithm);
  }
 catch (  NoSuchAlgorithmException e) {
    throw new RuntimeException(e.getMessage());
  }
}
 

Example 76

From project android_external_guava, under directory /src/com/google/common/io/.

Source file: ByteStreams.java

  15 
vote

/** 
 * Computes and returns the digest value for a supplied input stream. The digest object is reset when this method returns successfully.
 * @param supplier the input stream factory
 * @param md the digest object
 * @return the result of {@link MessageDigest#digest()} after updating thedigest object with all of the bytes in the stream
 * @throws IOException if an I/O error occurs
 */
public static byte[] getDigest(InputSupplier<? extends InputStream> supplier,final MessageDigest md) throws IOException {
  return readBytes(supplier,new ByteProcessor<byte[]>(){
    public boolean processBytes(    byte[] buf,    int off,    int len){
      md.update(buf,off,len);
      return true;
    }
    public byte[] getResult(){
      return md.digest();
    }
  }
);
}
 

Example 77

From project annotare2, under directory /app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/services/utils/.

Source file: DigestUtil.java

  15 
vote

public static String md5Hex(String str){
  try {
    byte[] md5=MessageDigest.getInstance("MD5").digest(str.getBytes(Charsets.UTF_8));
    return toHexString(md5);
  }
 catch (  NoSuchAlgorithmException e) {
    throw logUnexpected("md5Hex error",e);
  }
}
 

Example 78

From project archive-commons, under directory /archive-commons/src/main/java/org/archive/resource/arc/.

Source file: ARCResource.java

  15 
vote

public ARCResource(MetaData metaData,ResourceContainer container,ARCMetaData arcMetaData,InputStream raw){
  super(metaData.createChild(PAYLOAD_METADATA),container);
  envelope=metaData;
  this.arcMetaData=arcMetaData;
  this.raw=raw;
  metaData.putString(ENVELOPE_FORMAT,ENVELOPE_FORMAT_ARC);
  metaData.putLong(ARC_HEADER_LENGTH,arcMetaData.getHeaderLength());
  long leadingNL=arcMetaData.getLeadingNL();
  if (leadingNL > 0) {
    metaData.putLong(PAYLOAD_LEADING_SLOP_BYTES,leadingNL);
  }
  MetaData fields=metaData.createChild(ARC_HEADER_METADATA);
  fields.putString(URL_KEY,arcMetaData.getUrl());
  fields.putString(IP_KEY,arcMetaData.getIP());
  fields.putString(DATE_STRING_KEY,arcMetaData.getDateString());
  fields.putString(MIME_KEY,arcMetaData.getMime());
  fields.putLong(DECLARED_LENGTH_KEY,arcMetaData.getLength());
  countingIS=new CountingInputStream(new LimitInputStream(raw,arcMetaData.getLength()));
  try {
    digIS=new DigestInputStream(countingIS,MessageDigest.getInstance("sha1"));
  }
 catch (  NoSuchAlgorithmException e) {
    e.printStackTrace();
  }
}
 

Example 79

From project ardverk-commons, under directory /src/main/java/org/ardverk/security/.

Source file: MessageDigestUtils.java

  15 
vote

/** 
 * Creates and returns a  {@link MessageDigest} for the given algorithm.
 */
public static MessageDigest create(String algorithm){
  try {
    if (algorithm.equalsIgnoreCase(MessageDigestCRC32.NAME)) {
      return new MessageDigestCRC32();
    }
    return MessageDigest.getInstance(algorithm);
  }
 catch (  NoSuchAlgorithmException e) {
    throw new IllegalArgumentException("algorithm=" + algorithm,e);
  }
}
 

Example 80

From project aviator, under directory /src/main/java/com/googlecode/aviator/asm/commons/.

Source file: SerialVersionUIDAdder.java

  15 
vote

/** 
 * Returns the SHA-1 message digest of the given value.
 * @param value the value whose SHA message digest must be computed.
 * @return the SHA-1 message digest of the given value.
 */
protected byte[] computeSHAdigest(final byte[] value){
  try {
    return MessageDigest.getInstance("SHA").digest(value);
  }
 catch (  Exception e) {
    throw new UnsupportedOperationException(e);
  }
}
 

Example 81

From project BetterShop_1, under directory /src/me/jascotty2/lib/bukkit/.

Source file: FTP_PluginTracker.java

  15 
vote

public static String SUIDmd5Str(String txt) throws NoSuchAlgorithmException {
  if (txt == null) {
    txt="null";
  }
  byte hash[]=MessageDigest.getInstance("MD5").digest(txt.getBytes());
  String ret="";
  char chars[]={'q','w','e','r','t','y','u','i','o','p','a','s','d','f','g','h','j','k','l','z','x','c','v','b','n','m','~','1','2','3','4','5','6','7','8','9','0','-','+','Q','W','E','R','T','Y','U','I','O','P','A','S','D','F','G','H','J','K','L','Z','X','C','V','B','N','M'};
  for (  byte b : hash) {
    ret+=chars[((int)b + 255) % chars.length];
  }
  return ret;
}
 

Example 82

From project cascading, under directory /src/core/cascading/util/.

Source file: Util.java

  15 
vote

public static String createID(byte[] bytes){
  try {
    return getHex(MessageDigest.getInstance("MD5").digest(bytes));
  }
 catch (  NoSuchAlgorithmException exception) {
    throw new RuntimeException("unable to digest string");
  }
}
 

Example 83

From project CHMI, under directory /src/org/kaldax/lib/net/http/.

Source file: Downloader.java

  15 
vote

public Downloader(){
  lTotalBytesRead=0;
  lLastFileBytesRead=0;
  try {
    md=MessageDigest.getInstance("MD5");
  }
 catch (  NoSuchAlgorithmException ex) {
    md=null;
  }
}
 

Example 84

From project clojure, under directory /src/jvm/clojure/asm/commons/.

Source file: SerialVersionUIDAdder.java

  15 
vote

/** 
 * Returns the SHA-1 message digest of the given value.
 * @param value the value whose SHA message digest must be computed.
 * @return the SHA-1 message digest of the given value.
 */
protected byte[] computeSHAdigest(final byte[] value){
  try {
    return MessageDigest.getInstance("SHA").digest(value);
  }
 catch (  Exception e) {
    throw new UnsupportedOperationException(e);
  }
}
 

Example 85

From project copyartifact-plugin, under directory /src/main/java/hudson/plugins/copyartifact/.

Source file: FingerprintingCopyMethod.java

  15 
vote

private MessageDigest newMD5(){
  try {
    return MessageDigest.getInstance("MD5");
  }
 catch (  NoSuchAlgorithmException e) {
    throw new AssertionError(e);
  }
}