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

The following are Jave code examples for showing how to use getInstance() 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: sunbird-utils   File: OneWayHashing.java   View Source Code Vote up 6 votes
/**
    * This method will encrypt value using SHA-256 . it is one way encryption.
    * 
    * @param val String
    * @return String encrypted value or empty in case of exception
    */
public static String encryptVal(String val) {
	try {
		MessageDigest md = MessageDigest.getInstance("SHA-256");
		md.update(val.getBytes(StandardCharsets.UTF_8));
		byte byteData[] = md.digest();
		// convert the byte to hex format method 1
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < byteData.length; i++) {
			sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
		}
		ProjectLogger.log("encrypted value is==: " + sb.toString());
		return sb.toString();
	} catch (Exception e) {
		ProjectLogger.log("Error while encrypting", e);
	}
	return "";
}
 
Example 2
Project: nanocheeze   File: Torrent3.java   View Source Code Vote up 6 votes
public static byte[] createChecksum(String filename) throws Exception {
    InputStream fis = new FileInputStream(filename);

    byte[] buffer = new byte[1024];
    MessageDigest complete = MessageDigest.getInstance("MD5");
    int numRead;

    do {
        numRead = fis.read(buffer);
        if (numRead > 0) {
            complete.update(buffer, 0, numRead);
        }
    } while (numRead != -1);

    fis.close();
    return complete.digest();
}
 
Example 3
Project: jdk8u-jdk   File: CipherStreamClose.java   View Source Code Vote up 5 votes
public static void main(String[] args) throws Exception {
    MessageDigest digest = MessageDigest.getInstance("SHA1");
    SecretKeySpec key = new SecretKeySpec(
        DatatypeConverter.parseHexBinary(
        "12345678123456781234567812345678"), "AES");

    // Run 'message' through streamEncrypt
    byte[] se = streamEncrypt(message, key, digest);
    // 'digest' already has the value from the stream, just finish the op
    byte[] sd = digest.digest();
    digest.reset();
    // Run 'message' through blockEncrypt
    byte[] be = blockEncrypt(message, key);
    // Take digest of encrypted blockEncrypt result
    byte[] bd = digest.digest(be);
    // Verify both returned the same value
    if (!Arrays.equals(sd, bd)) {
        System.err.println("Stream: "+DatatypeConverter.printHexBinary(se)+
            "\t Digest: "+DatatypeConverter.printHexBinary(sd));
        System.err.println("Block : "+DatatypeConverter.printHexBinary(be)+
            "\t Digest: "+DatatypeConverter.printHexBinary(bd));
        throw new Exception("stream & block encryption does not match");
    }

    digest.reset();
    // Sanity check: Decrypt separately from stream to verify operations
    String bm = (String) blockDecrypt(be, key);
    if (message.compareTo(bm) != 0) {
        System.err.println("Expected: "+message+"\nBlock:    "+bm);
        throw new Exception("Block decryption does not match expected");
    }

    // Have decryption and digest included in the object stream
    String sm = (String) streamDecrypt(se, key, digest);
    if (message.compareTo(sm) != 0) {
        System.err.println("Expected: "+message+"\nStream:   "+sm);
        throw new Exception("Stream decryption does not match expected.");
    }
}
 
Example 4
Project: googles-monorepo-demo   File: MessageDigestAlgorithmBenchmark.java   View Source Code Vote up 5 votes
public MessageDigest getMessageDigest() {
  try {
    return MessageDigest.getInstance(algorithmName);
  } catch (NoSuchAlgorithmException e) {
    throw new AssertionError(e);
  }
}
 
Example 5
Project: q-mail   File: Authentication.java   View Source Code Vote up 5 votes
/**
 * Computes the response for CRAM-MD5 authentication mechanism given the user credentials and
 * the server-provided nonce.
 *
 * @param username The username.
 * @param password The password.
 * @param b64Nonce The nonce as base64-encoded byte array.
 * @return The CRAM-MD5 response as byte array.
 *
 * @throws MessagingException If something went wrong.
 *
 * @see <a href="https://tools.ietf.org/html/rfc2195">RFC 2195</a>
 */
public static byte[] computeCramMd5Bytes(String username, String password, byte[] b64Nonce)
throws MessagingException {

    try {
        byte[] nonce = Base64.decodeBase64(b64Nonce);

        byte[] secretBytes = password.getBytes();
        MessageDigest md = MessageDigest.getInstance("MD5");
        if (secretBytes.length > 64) {
            secretBytes = md.digest(secretBytes);
        }

        byte[] ipad = new byte[64];
        byte[] opad = new byte[64];
        System.arraycopy(secretBytes, 0, ipad, 0, secretBytes.length);
        System.arraycopy(secretBytes, 0, opad, 0, secretBytes.length);
        for (int i = 0; i < ipad.length; i++) ipad[i] ^= 0x36;
        for (int i = 0; i < opad.length; i++) opad[i] ^= 0x5c;

        md.update(ipad);
        byte[] firstPass = md.digest(nonce);

        md.update(opad);
        byte[] result = md.digest(firstPass);

        String plainCRAM = username + " " + Hex.encodeHex(result);
        byte[] b64CRAM = Base64.encodeBase64(plainCRAM.getBytes());

        return b64CRAM;

    } catch (Exception e) {
        throw new MessagingException("Something went wrong during CRAM-MD5 computation", e);
    }
}
 
Example 6
Project: wall.e   File: CodeKit.java   View Source Code Vote up 5 votes
/**
 * Build an hexadecimal SHA1 hash for a String
 * @param value The String to hash
 * @return An hexadecimal Hash
 */    
public static String hexSHA1(String value) {
    try {
        MessageDigest md;
        md = MessageDigest.getInstance("SHA-1");
        md.update(value.getBytes("utf-8"));
        byte[] digest = md.digest();
        return byteToHexString(digest);
    } catch (Exception ex) {
        throw new UnexpectedException(ex);
    }
}
 
Example 7
Project: k-framework   File: MD5.java   View Source Code Vote up 5 votes
/**
 * MD5编码
 * @param origin 原始字符串
 * @return 经过MD5加密之后的结果
 */
public static String MD5Encode(String origin) {
    String resultString = null;
    try {
        resultString = origin;
        MessageDigest md = MessageDigest.getInstance("MD5");
        resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return resultString;
}
 
Example 8
Project: utilsLibrary   File: MD5Utils.java   View Source Code Vote up 5 votes
/**
 * 生成md5
 * @param str
 * @return 返回md5 错误时返回 "".
 */
public static String getMD5(String str) {
    MessageDigest md5;
    try {
        md5 = MessageDigest.getInstance("MD5");
        md5.update(str.getBytes());
        byte[] m = md5.digest();
        return getString(m);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return "";
}
 
Example 9
Project: EyeShopping   File: PackageManagerUtils.java   View Source Code Vote up 5 votes
private static String signatureDigest(Signature sig) {
    byte[] signature = sig.toByteArray();
    try {
        MessageDigest md = MessageDigest.getInstance("SHA1");
        byte[] digest = md.digest(signature);
        return BaseEncoding.base16().lowerCase().encode(digest);
    } catch (NoSuchAlgorithmException e) {
        return null;
    }
}
 
Example 10
Project: ss-java   File: RC4MD5Crypto.java   View Source Code Vote up 5 votes
@Override
protected CipherParameters getCipherParameter(byte[] iv) {
    MessageDigest md5;
    try {
        md5 = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
    md5.update(getSecretKey().getEncoded());
    md5.update(iv);
    return new KeyParameter(md5.digest());
}
 
Example 11
Project: ethereum-bytecode-analyzer   File: HashUtil.java   View Source Code Vote up 5 votes
/**
 * hashing chunk of the data
 * 
 * @param input
 *            - data for hash
 * @param start
 *            - start of hashing chunk
 * @param length
 *            - length of hashing chunk
 * @return - keccak hash of the chunk
 */
public static byte[] sha3(byte[] input, int start, int length) {
    MessageDigest digest;
    try {
        digest = MessageDigest.getInstance(HASH_256_ALGORITHM_NAME, CRYPTO_PROVIDER);
        digest.update(input, start, length);
        return digest.digest();
    } catch (NoSuchAlgorithmException e) {
        log.error("Can't find such algorithm", e);
        throw new RuntimeException(e);
    }
}
 
Example 12
Project: Android-Client   File: Tools.java   View Source Code Vote up 5 votes
@Nullable
public static String computeSHAHash(String string) {
    MessageDigest mdSha1 = null;
    try {
        mdSha1 = MessageDigest.getInstance("SHA-1");
        mdSha1.update(string.getBytes("UTF-8"));

        byte[] data = mdSha1.digest();
        return convertToHex(data);

    } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
        Log.e(TAG, "Error initializing SHA1 message digest");
        return null;
    }
}
 
Example 13
Project: springboot-spwa-gae-demo   File: EncoderTest.java   View Source Code Vote up 5 votes
@Test
public void shouldEncodeWithMd5ThenHex() throws NoSuchAlgorithmException {
    String input = "My input string";
    MessageDigest md5 = MessageDigest.getInstance("MD5");
    String expected = new String(Hex.encodeHex(md5.digest(input.getBytes())));
    assertThat(new Encoder(input).md5().hex().string(), is(expected));
}
 
Example 14
Project: Rxjava2.0Demo   File: MD5Util.java   View Source Code Vote up 5 votes
/**
 * 1.对文本进行32位小写MD5加密
 *
 * @param plainText
 *            要进行加密的文本
 * @return 加密后的内容
 */
public static String textToMD5L32(String plainText) {
    String result = null;
    // 首先判断是否为空
    if (TextUtils.isEmpty(plainText)) {
        return null;
    }
    try {
        // 首先进行实例化和初始化
        MessageDigest md = MessageDigest.getInstance("MD5");
        // 得到一个操作系统默认的字节编码格式的字节数组
        byte[] btInput = plainText.getBytes();
        // 对得到的字节数组进行处理
        md.update(btInput);
        // 进行哈希计算并返回结果
        byte[] btResult = md.digest();
        // 进行哈希计算后得到的数据的长度
        StringBuffer sb = new StringBuffer();
        for (byte b : btResult) {
            int bt = b & 0xff;
            if (bt < 16) {
                sb.append(0);
            }
            sb.append(Integer.toHexString(bt));
        }
        result = sb.toString();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return result;
}
 
Example 15
Project: utils-android   File: EncryptUtils.java   View Source Code Vote up 5 votes
public static byte[] hash(final byte[] data, final String algorithm) {
    if (data == null || data.length <= 0) {
        return null;
    }
    try {
        MessageDigest md = MessageDigest.getInstance(algorithm);
        md.update(data);
        return md.digest();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 16
Project: PaoMovie   File: HttpUtil.java   View Source Code Vote up 5 votes
/**
 * 获取文本内容的SHA1摘要值
 * 
 * @param params
 * @param userPwd
 * 
 * @return
 */
public static String getSHA1(Map<String, String> params, String userPwd) {
	StringBuilder text = new StringBuilder();

	// 使用sha1加密,签名内容及顺序如下:
	// loginName+userPwd+TimeStamp+IBeaconId+IBeaconActionId+Power+BatteryLevel+CurrentDistance+IBSentTimeStamp+TickTack+IBTimeStamp
	// 变量userPwd的值:3D4F2BF07DC1BE38B20CD6E46949A1071F9D0E3D

	text.append(params.get("loginName"));
	text.append(userPwd);
	text.append(params.get("TimeStamp"));
	text.append(params.get("IBeaconId"));
	text.append(params.get("IBeaconActionId"));
	text.append(params.get("Power"));
	text.append(params.get("BatteryLevel"));
	text.append(params.get("CurrentDistance"));
	text.append(params.get("IBSentTimeStamp"));
	text.append(params.get("TickTack"));
	text.append(params.get("IBTimeStamp"));

	try {

		MessageDigest sha = MessageDigest.getInstance("SHA-1");
		sha.update(text.toString().getBytes("UTF-8"), 0, text.toString().length());
		String ret = byte2hex(sha.digest());

		return ret;
	} catch (Exception exp) {
		exp.printStackTrace();
		return "";
	}
}
 
Example 17
Project: AI-Powered-Intelligent-Banking-Platform   File: AuthorizationManager.java   View Source Code Vote up 5 votes
/**
 * Hash a string based on the SHA-256 message digest
 * @param password
 * @return
 */
public static byte[] getHash(String password) {
    MessageDigest digest=null;
    try {
        digest = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException e1) {
        e1.printStackTrace();
    }
    digest.reset();
    byte[] response = digest.digest(password.getBytes());

    return response;
}
 
Example 18
Project: AppCenter-Test-Espresso-Extensions   File: ShortIdentifier.java   View Source Code Vote up 4 votes
private byte[] calcSha1(String input) throws NoSuchAlgorithmException {
    MessageDigest digest = MessageDigest.getInstance("SHA-1");
    return digest.digest(input.getBytes());
}
 
Example 19
Project: FApkSigner   File: V1SchemeVerifier.java   View Source Code Vote up 4 votes
private static MessageDigest getMessageDigest(String algorithm)
        throws NoSuchAlgorithmException {
    return MessageDigest.getInstance(algorithm);
}
 
Example 20
Project: automat   File: SHACoder.java   View Source Code Vote up 3 votes
/**
 * SHA-1加密
 * 
 * @param data 待加密数据
 * @return byte[] 消息摘要
 * @throws Exception
 */
public static byte[] encodeSHA(byte[] data) throws Exception {
	// 初始化MessageDigest
	MessageDigest md = MessageDigest.getInstance("SHA");
	// 执行消息摘要
	return md.digest(data);
}