Java Code Examples for java.security.MessageDigest.update()

The following are Jave code examples for showing how to use update() of the java.security.MessageDigest class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: GroupControlDroidClient   File: MD5Util.java   View Source Code Vote up 6 votes
public final static String MD5(String s) {
    char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
    try {
        byte[] btInput = s.getBytes();
        // 获得MD5摘要算法的 MessageDigest 对象
        MessageDigest mdInst = MessageDigest.getInstance("MD5");
        // 使用指定的字节更新摘要
        mdInst.update(btInput);
        // 获得密文
        byte[] md = mdInst.digest();
        // 把密文转换成十六进制的字符串形式
        int j = md.length;
        char str[] = new char[j * 2];
        int k = 0;
        for (int i = 0; i < j; i++) {
            byte byte0 = md[i];
            str[k++] = hexDigits[byte0 >>> 4 & 0xf];
            str[k++] = hexDigits[byte0 & 0xf];
        }
        return new String(str);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 2
Project: AES-with-CBC   File: AES.java   View Source Code Vote up 6 votes
public static byte[] decrypt(byte[] encryptedIvTextBytes, String key) throws Exception {
    byte ivSize = 16;
    byte keySize = 16;
    byte[] iv = new byte[ivSize];
    System.arraycopy(encryptedIvTextBytes, 0, iv, 0, iv.length);
    IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
    int encryptedSize = encryptedIvTextBytes.length - ivSize;
    byte[] encryptedBytes = new byte[encryptedSize];
    System.arraycopy(encryptedIvTextBytes, ivSize, encryptedBytes, 0, encryptedSize);
    byte[] keyBytes = new byte[keySize];
    MessageDigest md = MessageDigest.getInstance("SHA-256");
    md.update(key.getBytes());
    System.arraycopy(md.digest(), 0, keyBytes, 0, keyBytes.length);
    SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
    Cipher cipherDecrypt = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipherDecrypt.init(2, secretKeySpec, ivParameterSpec);
    byte[] decrypted = cipherDecrypt.doFinal(encryptedBytes);
    return decrypted;
}
 
Example 3
Project: FeedFire   File: FacebookSign.java   View Source Code Vote up 6 votes
public static void keyHash(Context context){

        // Add code to print out the key hash
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(
                    "barreto.alessandro.feedlist",
                    PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
            }
        } catch (PackageManager.NameNotFoundException | NoSuchAlgorithmException ignored) {
            Log.e("Facebook",ignored.getMessage());
        }

    }
 
Example 4
Project: datarouter   File: DefaultSignatureValidator.java   View Source Code Vote up 6 votes
private byte[] signWithoutSettingParameterOrder(Map<String, String> map, HttpEntity entity){
	// TODO signature length should be constant. currently signature length is proportional to number of parameters.
	ByteArrayOutputStream signature = new ByteArrayOutputStream();
	try{
		MessageDigest md = MessageDigest.getInstance(HASHING_ALGORITHM);
		for(Entry<String,String> entry : map.entrySet()){
			String parameterName = entry.getKey();
			if(parameterName.equals(SecurityParameters.SIGNATURE) || "submitAction".equals(parameterName)){
				continue;
			}
			String value = entry.getValue();
			String keyValue = parameterName.concat(value == null ? "" : value);
			String keyValueSalt = keyValue.concat(salt);
			md.update(keyValueSalt.getBytes(StandardCharsets.UTF_8));
			signature.write(md.digest());
		}

		if(entity != null){
			byte[] bytes = EntityUtils.toByteArray(entity);
			md.update(bytes);
			md.update(salt.getBytes(StandardCharsets.UTF_8));
			signature.write(md.digest());
		}
	}catch(IOException | NoSuchAlgorithmException e){
		throw new RuntimeException(e);
	}
	return signature.toByteArray();
}
 
Example 5
Project: PlusGram   File: Utilities.java   View Source Code Vote up 6 votes
public static byte[] computeSHA1(ByteBuffer convertme, int offset, int len) {
    int oldp = convertme.position();
    int oldl = convertme.limit();
    try {
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        convertme.position(offset);
        convertme.limit(len);
        md.update(convertme);
        return md.digest();
    } catch (Exception e) {
        FileLog.e("tmessages", e);
    } finally {
        convertme.limit(oldl);
        convertme.position(oldp);
    }
    return new byte[20];
}
 
Example 6
Project: Mevius-IO   File: MeviusCipher.java   View Source Code Vote up 6 votes
private void md5action(String s) {
	try {
		MessageDigest md = MessageDigest.getInstance("MD5");
		md.update(s.getBytes());
		byte[] buff = md.digest();
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < buff.length; i++) {
			sb.append(Integer.toString((buff[i] & 0xff) + 0x100, 16).substring(1));
		}
		stringdata = sb.toString();
		bytedata = new byte[] {};
	} catch (NoSuchAlgorithmException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
 
Example 7
Project: Cubes_2   File: AndroidModLoader.java   View Source Code Vote up 6 votes
public static String hashFile(FileHandle fileHandle) throws Exception {
  InputStream inputStream = fileHandle.read();
  try {
    MessageDigest digest = MessageDigest.getInstance("SHA-256");

    byte[] bytesBuffer = new byte[1024];
    int bytesRead;
int n =inputStream.read(bytesBuffer);
    while ((bytesRead = n) != -1) {
      digest.update(bytesBuffer, 0, bytesRead);
      n=inputStream.read(bytesBuffer);
    }

    byte[] hashedBytes = digest.digest();
    return convertByteArrayToHexString(hashedBytes);
  } catch (IOException ex) {
    throw new CubesException("Could not generate hash from file " + fileHandle.path(), ex);
  } finally {
    StreamUtils.closeQuietly(inputStream);
  }
}
 
Example 8
Project: DWSurvey   File: DigestUtils.java   View Source Code Vote up 6 votes
private static String digest(InputStream input, String algorithm) throws IOException {
	try {
		MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
		int bufferLength = 1024;
		byte[] buffer = new byte[bufferLength];
		int read = input.read(buffer, 0, bufferLength);

		while (read > -1) {
			messageDigest.update(buffer, 0, read);
			read = input.read(buffer, 0, bufferLength);
		}

		return EncodeUtils.encodeHex(messageDigest.digest());

	} catch (GeneralSecurityException e) {
		throw ExceptionUtils.unchecked(e);
	}
}
 
Example 9
Project: Ins_fb_pictureSpider_WEB   File: MD5.java   View Source Code Vote up 6 votes
/**
 *
 * @param plainText 明文
 * @return 32位密文
 */
public static String encryption(String plainText) {
    String re_md5 = new String();
    try {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(plainText.getBytes());
        byte b[] = md.digest();
        int i;
        StringBuffer buf = new StringBuffer("");
        for (int offset = 0; offset < b.length; offset++) {
            i = b[offset];
            if (i < 0)
                i += 256;
            if (i < 16)
                buf.append("0");
            buf.append(Integer.toHexString(i));
        }
        re_md5 = buf.toString();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return re_md5;
}
 
Example 10
Project: Android-Code-Demos   File: DiskCacheUtil.java   View Source Code Vote up 5 votes
public static String getMD5String(String key) {
    String cacheKey;
    try {
        final MessageDigest mDigest = MessageDigest.getInstance("MD5");
        mDigest.update(key.getBytes());
        cacheKey = bytesToHexString(mDigest.digest());
    } catch (NoSuchAlgorithmException e) {
        cacheKey = String.valueOf(key.hashCode());
    }
    return cacheKey;
}
 
Example 11
Project: springreplugin   File: SecurityUtil.java   View Source Code Vote up 5 votes
public static final byte[] MD5(InputStream in) throws NoSuchAlgorithmException, IOException {
    MessageDigest digest = MessageDigest.getInstance("MD5");
    byte buffer[] = new byte[4096];
    int rc = 0;
    while ((rc = in.read(buffer)) >= 0) {
        if (rc > 0) {
            digest.update(buffer, 0, rc);
        }
    }
    return digest.digest();
}
 
Example 12
Project: add_to_evernote_note   File: EvernoteUtil.java   View Source Code Vote up 5 votes
@SuppressLint("PackageManagerGetSignatures")
private static EvernoteInstallStatus validateSignature(PackageManager packageManager) {
    MessageDigest digest = getSha256Digest();
    if (digest == null) {
        // can't compare signatures
        return EvernoteInstallStatus.NOT_INSTALLED;
    }

    PackageInfo packageInfo;
    try {
        packageInfo = packageManager.getPackageInfo(PACKAGE_NAME, PackageManager.GET_SIGNATURES);
    } catch (PackageManager.NameNotFoundException e) {
        return EvernoteInstallStatus.NOT_INSTALLED;
    }

    if (packageInfo.signatures == null || packageInfo.signatures.length == 0) {
        // must have at least one signature
        return EvernoteInstallStatus.NOT_INSTALLED;
    }

    // check all signatures
    for (Signature signature : packageInfo.signatures) {
        digest.update(signature.toByteArray());
        String appSignature = encodeBase64(digest.digest());
        if (EVERNOTE_SIGNATURE.equals(appSignature)) {
            return EvernoteInstallStatus.INSTALLED;
        }
    }
    return EvernoteInstallStatus.NOT_INSTALLED;
}
 
Example 13
Project: boohee_v5.6   File: Util.java   View Source Code Vote up 5 votes
private static boolean a(Context context) {
    try {
        PackageInfo packageInfo = context.getPackageManager().getPackageInfo("com.tencent" +
                ".mtt", 64);
        String str = packageInfo.versionName;
        if (SystemUtils.compareVersion(str, "4.3") < 0 || str.startsWith("4.4")) {
            return false;
        }
        Signature[] signatureArr = packageInfo.signatures;
        if (signatureArr == null) {
            return false;
        }
        try {
            MessageDigest instance = MessageDigest.getInstance(Coder.KEY_MD5);
            instance.update(signatureArr[0].toByteArray());
            String toHexString = toHexString(instance.digest());
            instance.reset();
            str = "d8391a394d4a179e6fe7bdb8a301258b";
            if (toHexString.equals("d8391a394d4a179e6fe7bdb8a301258b")) {
                return true;
            }
            return false;
        } catch (NoSuchAlgorithmException e) {
            f.e(a, "isQQBrowerAvailable has exception: " + e.getMessage());
            return false;
        }
    } catch (NameNotFoundException e2) {
        return false;
    }
}
 
Example 14
Project: OSchina_resources_android   File: DiskLruCacheUtil.java   View Source Code Vote up 5 votes
/**
 * 传入缓存的key值,以得到相应的MD5值
 *
 * @param key
 * @return
 */
public static String hashKeyForDisk(String key) {
    String cacheKey;
    try {
        final MessageDigest mDigest = MessageDigest.getInstance("MD5");
        mDigest.update(key.getBytes());
        cacheKey = bytesToHexString(mDigest.digest());
    } catch (NoSuchAlgorithmException e) {
        cacheKey = String.valueOf(key.hashCode());
    }
    return cacheKey;
}
 
Example 15
Project: jshERP   File: Tools.java   View Source Code Vote up 5 votes
/**
    * 获取一个字符串的MD5
    * @param msg
    * @return 加密后的MD5字符串
    * @throws NoSuchAlgorithmException 
    */
   public static String md5Encryp(String msg) throws NoSuchAlgorithmException 
{
       // 生成一个MD5加密计算摘要
       MessageDigest md = MessageDigest.getInstance("MD5");
       // 计算md5函数
       md.update(msg.getBytes());
       return new BigInteger(1, md.digest()).toString(16);
   }
 
Example 16
Project: CourseraBitcoin   File: Block.java   View Source Code Vote up 5 votes
public void finalize() {
    try {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(getRawBlock());
        hash = md.digest();
    } catch (NoSuchAlgorithmException x) {
        x.printStackTrace(System.err);
    }
}
 
Example 17
Project: bird-java   File: SecurityHelper.java   View Source Code Vote up 5 votes
public final static String MD5(String pwd) {
    //用于加密的字符
    char md5String[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            'a', 'b', 'c', 'd', 'e', 'f' };
    try {
        //使用平台的默认字符集将此 String 编码为 byte序列,并将结果存储到一个新的 byte数组中
        byte[] btInput = pwd.getBytes();

        //信息摘要是安全的单向哈希函数,它接收任意大小的数据,并输出固定长度的哈希值。
        MessageDigest mdInst = MessageDigest.getInstance("MD5");

        //MessageDigest对象通过使用 update方法处理数据, 使用指定的byte数组更新摘要
        mdInst.update(btInput);

        // 摘要更新之后,通过调用digest()执行哈希计算,获得密文
        byte[] md = mdInst.digest();

        // 把密文转换成十六进制的字符串形式
        int j = md.length;
        char str[] = new char[j * 2];
        int k = 0;
        for (int i = 0; i < j; i++) {   //  i = 0
            byte byte0 = md[i];  //95
            str[k++] = md5String[byte0 >>> 4 & 0xf];    //    5
            str[k++] = md5String[byte0 & 0xf];   //   F
        }

        //返回经过加密后的字符串
        return new String(str);

    } catch (Exception e) {
        return null;
    }
}
 
Example 18
Project: cryptocurrency_coursera   File: Transaction.java   View Source Code Vote up 5 votes
public void finalize() {
    try {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(getRawTx());
        hash = md.digest();
    } catch (NoSuchAlgorithmException x) {
        x.printStackTrace(System.err);
    }
}
 
Example 19
Project: nat-network-transfer   File: Util.java   View Source Code Vote up 4 votes
public static String getMD5(String val) throws NoSuchAlgorithmException {
    MessageDigest md5 = MessageDigest.getInstance("MD5");
    md5.update(val.getBytes());
    byte[] m = md5.digest();//加密
    return getString(m);
}
 
Example 20
Project: nat-geolocation   File: Util.java   View Source Code Vote up 4 votes
public static String getMD5(String val) throws NoSuchAlgorithmException {
    MessageDigest md5 = MessageDigest.getInstance("MD5");
    md5.update(val.getBytes());
    byte[] m = md5.digest();//加密
    return getString(m);
}