Java 类java.security.MessageDigest 实例源码
项目:ibm-cos-sdk-java
文件:Base16CodecTest.java
@Test
public void testCodecConsistency()
throws NoSuchAlgorithmException, UnsupportedEncodingException
{
byte[] decoded = null;
for (int h=0; h < 1000; h++) {
byte[] digest = MessageDigest.getInstance("SHA-1").digest(
UUID.randomUUID().toString().getBytes("UTF-8")
);
String b16Encoded = Base16.encodeAsString(digest);
{
decoded = Base16.decode(b16Encoded);
Assert.assertTrue(Arrays.equals(decoded, digest));
decoded = Base16Lower.decode(b16Encoded);
Assert.assertTrue(Arrays.equals(decoded, digest));
}
{ // test decoding case insensitivity
decoded = Base16.decode(b16Encoded.toLowerCase());
Assert.assertTrue(Arrays.equals(decoded, digest));
decoded = Base16Lower.decode(b16Encoded.toLowerCase());
Assert.assertTrue(Arrays.equals(decoded, digest));
}
}
}
项目:lams
文件:NTLMEngineImpl.java
HMACMD5(byte[] key) throws NTLMEngineException {
try {
md5 = MessageDigest.getInstance("MD5");
} catch (Exception ex) {
// Umm, the algorithm doesn't exist - throw an
// NTLMEngineException!
throw new NTLMEngineException(
"Error getting md5 message digest implementation: " + ex.getMessage(), ex);
}
// Initialize the pad buffers with the key
ipad = new byte[64];
opad = new byte[64];
int keyLength = key.length;
if (keyLength > 64) {
// Use MD5 of the key instead, as described in RFC 2104
md5.update(key);
key = md5.digest();
keyLength = key.length;
}
int i = 0;
while (i < keyLength) {
ipad[i] = (byte) (key[i] ^ (byte) 0x36);
opad[i] = (byte) (key[i] ^ (byte) 0x5c);
i++;
}
while (i < 64) {
ipad[i] = (byte) 0x36;
opad[i] = (byte) 0x5c;
i++;
}
// Very important: update the digest with the ipad buffer
md5.reset();
md5.update(ipad);
}
项目:FaceDistinguish
文件:MessageDigestUtil.java
/**
* 先进行MD5摘要再进行Base64编码获取摘要字符串
*
* @return
*/
public static String base64AndMD5(byte[] bytes) {
if (bytes == null) {
throw new IllegalArgumentException("bytes can not be null");
}
try {
final MessageDigest md = MessageDigest.getInstance("MD5");
md.reset();
md.update(bytes);
final Base64 base64 = new Base64();
final byte[] enbytes = base64.encode(md.digest());
return new String(enbytes);
} catch (final NoSuchAlgorithmException e) {
throw new IllegalArgumentException("unknown algorithm MD5");
}
}
项目:nanocheeze
文件:Torrent3.java
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();
}
项目:CrypDist
文件:MerkleTree.java
private String SHA256(String data)
{
String signature = null;
try
{
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(data.getBytes("UTF-8"));
byte[] bytes = md.digest(data.getBytes("UTF-8"));
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; i++)
sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
signature = sb.toString();
}
catch (NoSuchAlgorithmException | UnsupportedEncodingException e)
{
}
return signature;
}
项目:burstcoin
文件:Crypto.java
public static boolean verify(byte[] signature, byte[] message, byte[] publicKey, boolean enforceCanonical) {
if (enforceCanonical && !Curve25519.isCanonicalSignature(signature)) {
Logger.logDebugMessage("Rejecting non-canonical signature");
return false;
}
if (enforceCanonical && !Curve25519.isCanonicalPublicKey(publicKey)) {
Logger.logDebugMessage("Rejecting non-canonical public key");
return false;
}
byte[] Y = new byte[32];
byte[] v = new byte[32];
System.arraycopy(signature, 0, v, 0, 32);
byte[] h = new byte[32];
System.arraycopy(signature, 32, h, 0, 32);
Curve25519.verify(Y, v, h, publicKey);
MessageDigest digest = Crypto.sha256();
byte[] m = digest.digest(message);
digest.update(m);
byte[] h2 = digest.digest(Y);
return Arrays.equals(h, h2);
}
项目:DouyuDanmu
文件:Danmu.java
public static String MD5(String s) {
char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
try {
MessageDigest mdInst = MessageDigest.getInstance("MD5");
byte[] md = mdInst.digest(s.getBytes());
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (byte b : md) {
str[k++] = hexDigits[b >>> 4 & 0xf];
str[k++] = hexDigits[b & 0xf];
}
return new String(str).toLowerCase();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
项目:Lucid2.0
文件:LoginCrypto.java
private static String hashWithDigest(final String in, final String digest) {
try {
MessageDigest Digester = MessageDigest.getInstance(digest);
Digester.update(in.getBytes("UTF-8"), 0, in.length());
byte[] sha1Hash = Digester.digest();
return toSimpleHexString(sha1Hash);
} catch (NoSuchAlgorithmException ex) {
throw new RuntimeException("Hashing the password failed", ex);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Encoding the string failed", e);
}
}
项目:openjdk-jdk10
文件:SignatureFileVerifier.java
/** get digest from cache */
private MessageDigest getDigest(String algorithm)
throws SignatureException {
if (createdDigests == null)
createdDigests = new HashMap<>();
MessageDigest digest = createdDigests.get(algorithm);
if (digest == null) {
try {
digest = MessageDigest.getInstance(algorithm);
createdDigests.put(algorithm, digest);
} catch (NoSuchAlgorithmException nsae) {
// ignore
}
}
return digest;
}
项目:karanotes
文件:EncryptUtil.java
public static String MD5Encode(String origin) throws Exception{
String resultString = null;
resultString = new String(origin);
MessageDigest md = MessageDigest.getInstance("MD5");
resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
return resultString;
}
项目:logistimo-web-service
文件:TransactionUtil.java
public static String checksum(Long domainId, List<ITransaction> list) {
xLogger.fine("Entered checksum: {0}", (list == null ? "NULL" : list.size()));
Iterator<ITransaction> it = list.iterator();
try {
MessageDigest md = MessageDigest.getInstance("MD5");
while (it.hasNext()) {
ITransaction trans = it.next();
if (trans.getDomainId() == null) {
trans.setDomainId(domainId);
}
byte[] fingerprint = trans.fingerprint();
if (fingerprint != null) {
md.update(fingerprint);
}
}
return new String(Hex.encodeHex(md.digest()));
} catch (Exception e) {
xLogger.warn("{0} when getting checksum: {1}", e.getClass().getName(), e.getMessage());
return null;
}
}
项目:rebase-android
文件:Md5.java
public static String md5(byte[] source) {
try {
// Create MD5 Hash
MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
digest.update(source);
byte messageDigest[] = digest.digest();
// Create Hex String
StringBuilder hexString = new StringBuilder();
for (byte aMessageDigest : messageDigest) {
hexString.append(Integer.toHexString(0xFF & aMessageDigest));
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
项目:lazycat
文件:WebSocketServlet.java
private String getWebSocketAccept(String key) throws ServletException {
MessageDigest sha1Helper = sha1Helpers.poll();
if (sha1Helper == null) {
try {
sha1Helper = MessageDigest.getInstance("SHA1");
} catch (NoSuchAlgorithmException e) {
throw new ServletException(e);
}
}
sha1Helper.reset();
sha1Helper.update(key.getBytes(B2CConverter.ISO_8859_1));
String result = Base64.encode(sha1Helper.digest(WS_ACCEPT));
sha1Helpers.add(sha1Helper);
return result;
}
项目:19porn
文件:Codec.java
/**
* 十六进制
*
* @param buffer
* @return
*/
public static String getMessageDigest(byte[] buffer) {
char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
try {
MessageDigest mdTemp = MessageDigest.getInstance(Algorithm.MD5.getType());
mdTemp.update(buffer);
byte[] md = mdTemp.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) {
return null;
}
}
项目:iot-plat
文件:Tools.java
public static String md5(byte[] plainText) {
String result = "";
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(plainText);
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));
}
result = buf.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
return result;
}
项目:iosched-reader
文件:CloudFileManager.java
static public byte[] calulateHash(JsonElement contents) {
MessageDigest md;
try {
md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
throw new InternalError("MD5 MessageDigest is not available");
}
OutputStream byteSink = new OutputStream() {
@Override
public void write(int b) throws IOException {
// ignore, since this is only used to calculate MD5
}
};
DigestOutputStream dis = new DigestOutputStream(byteSink, md);
new Gson().toJson(contents, new OutputStreamWriter(dis, Charset.forName(DEFAULT_CHARSET_NAME)));
return dis.getMessageDigest().digest();
}
项目:banana
文件:WeChatUtil.java
/**
* @param decript 要加密的字符串
* @return 加密的字符串
* MD5加密
*/
public final static String toMD5(String decript) {
char hexDigits[] = { // 用来将字节转换成 16 进制表示的字符
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
'e', 'f'};
try {
byte[] strTemp = decript.getBytes();
MessageDigest mdTemp = MessageDigest.getInstance("toMD5");
mdTemp.update(strTemp);
byte tmp[] = mdTemp.digest(); // toMD5 的计算结果是一个 128 位的长整数,
// 用字节表示就是 16 个字节
char strs[] = new char[16 * 2]; // 每个字节用 16 进制表示的话,使用两个字符,
// 所以表示成 16 进制需要 32 个字符
int k = 0; // 表示转换结果中对应的字符位置
for (int i = 0; i < 16; i++) { // 从第一个字节开始,对 toMD5 的每一个字节
// 转换成 16 进制字符的转换
byte byte0 = tmp[i]; // 取第 i 个字节
strs[k++] = hexDigits[byte0 >>> 4 & 0xf]; // 取字节中高 4 位的数字转换,
// >>> 为逻辑右移,将符号位一起右移
strs[k++] = hexDigits[byte0 & 0xf]; // 取字节中低 4 位的数字转换
}
return new String(strs).toUpperCase(); // 换后的结果转换为字符串
} catch (Exception e) {
return null;
}
}
项目:GitHub
文件:BitmapTransformationTest.java
@Test
public void testReturnsGivenResourceWhenBitmapNotTransformed() {
BitmapTransformation transformation = new BitmapTransformation() {
@Override
public void updateDiskCacheKey(MessageDigest messageDigest) { }
@Override
protected Bitmap transform(@NonNull BitmapPool pool, @NonNull Bitmap toTransform,
int outWidth, int outHeight) {
return toTransform;
}
};
Resource<Bitmap> resource = mockResource(100, 100);
assertEquals(resource, transformation.transform(context, resource, 1, 1));
}
项目:googles-monorepo-demo
文件:MessageDigestHashFunctionTest.java
private static void assertMessageDigestHashing(byte[] input, String algorithmName) {
try {
MessageDigest digest = MessageDigest.getInstance(algorithmName);
assertEquals(
HashCode.fromBytes(digest.digest(input)),
ALGORITHMS.get(algorithmName).hashBytes(input));
for (int bytes = 4; bytes <= digest.getDigestLength(); bytes++) {
assertEquals(
HashCode.fromBytes(Arrays.copyOf(digest.digest(input), bytes)),
new MessageDigestHashFunction(algorithmName, bytes, algorithmName).hashBytes(input));
}
try {
int maxSize = digest.getDigestLength();
new MessageDigestHashFunction(algorithmName, maxSize + 1, algorithmName);
fail();
} catch (IllegalArgumentException expected) {
}
} catch (NoSuchAlgorithmException nsae) {
throw new AssertionError(nsae);
}
}
项目:FastBootWeixin
文件:CryptUtils.java
/**
* SHA 加密
*
* @param data 需要加密的字符串
* @return 加密之后的字符串
*/
public static String encryptSHA1(String data) {
// 验证传入的字符串
if (StringUtils.isEmpty(data)) {
return "";
}
// 创建具有指定算法名称的信息摘要
MessageDigest sha = null;
try {
sha = MessageDigest.getInstance(KEY_SHA1);
} catch (NoSuchAlgorithmException e) {
throw new WxAppException(e);
}
// 使用指定的字节数组对摘要进行最后更新
sha.update(data.getBytes(StandardCharsets.UTF_8));
// 完成摘要计算
byte[] bytes = sha.digest();
// 将得到的字节数组变成字符串返回
return byteArrayToHexString(bytes);
}
项目:android-apkbox
文件:ApkMd5.java
public final static String md5(String str) {
char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
try {
byte[] strTemp = str.getBytes();
MessageDigest mdTemp = MessageDigest.getInstance("MD5");
mdTemp.update(strTemp);
byte tmp[] = mdTemp.digest();
char strs[] = new char[16 * 2];
int k = 0;
for (int i = 0; i < 16; i++) {
byte byte0 = tmp[i];
strs[k++] = hexDigits[byte0 >>> 4 & 0xf];
strs[k++] = hexDigits[byte0 & 0xf];
}
return new String(strs).toUpperCase();
} catch (Exception e) {
return null;
}
}
项目:lams
文件:SAML1ArtifactType0001Builder.java
/** {@inheritDoc} */
public SAML1ArtifactType0001 buildArtifact(
SAMLMessageContext<RequestAbstractType, Response, NameIdentifier> requestContext, Assertion assertion) {
try {
MessageDigest sha1Digester = MessageDigest.getInstance("SHA-1");
byte[] source = sha1Digester.digest(requestContext.getLocalEntityId().getBytes());
SecureRandom handleGenerator = SecureRandom.getInstance("SHA1PRNG");
byte[] assertionHandle = new byte[20];
handleGenerator.nextBytes(assertionHandle);
return new SAML1ArtifactType0001(source, assertionHandle);
} catch (NoSuchAlgorithmException e) {
log.error("JVM does not support required cryptography algorithms.", e);
throw new InternalError("JVM does not support required cryptography algorithms: SHA-1 and/or SHA1PRNG.");
}
}
项目:WeatherSystem
文件:MD5Util.java
/**
* 生成md5
*
* @param message
* @return
*/
public static String getMD5(String message) {
String md5str = "";
try {
// 1 创建一个提供信息摘要算法的对象,初始化为md5算法对象
MessageDigest md = MessageDigest.getInstance("MD5");
// 2 将消息变成byte数组
byte[] input = message.getBytes();
// 3 计算后获得字节数组,这就是那128位了
byte[] buff = md.digest(input);
// 4 把数组每一字节(一个字节占八位)换成16进制连成md5字符串
md5str = bytesToHex(buff);
} catch (Exception e) {
e.printStackTrace();
}
return md5str;
}
项目:Cable-Android
文件:ConversationAdapter.java
public ConversationAdapter(@NonNull Context context,
@NonNull MasterSecret masterSecret,
@NonNull Locale locale,
@Nullable ItemClickListener clickListener,
@Nullable Cursor cursor,
@NonNull Recipients recipients)
{
super(context, cursor);
try {
this.masterSecret = masterSecret;
this.locale = locale;
this.clickListener = clickListener;
this.recipients = recipients;
this.inflater = LayoutInflater.from(context);
this.db = DatabaseFactory.getMmsSmsDatabase(context);
this.calendar = Calendar.getInstance();
this.digest = MessageDigest.getInstance("SHA1");
setHasStableIds(true);
} catch (NoSuchAlgorithmException nsae) {
throw new AssertionError("SHA1 isn't supported!");
}
}
项目:AndroidBasicLibs
文件:MD5.java
/**
* 十六进制
*
* @param buffer
* @return
*/
public static String getMessageDigest(byte[] buffer) {
char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
try {
MessageDigest mdTemp = MessageDigest.getInstance(CipherType.MD5.getType());
mdTemp.update(buffer);
byte[] md = mdTemp.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) {
return null;
}
}
项目:fort_j
文件:Strings.java
@ApiMethod
@Comment(value = "Hash the bytes with the given algorithm")
public static String hash(byte[] byteArr, String algorithm)
{
try
{
MessageDigest digest = MessageDigest.getInstance(algorithm);
digest.update(byteArr);
byte[] bytes = digest.digest();
String hex = (new HexBinaryAdapter()).marshal(bytes);
return hex;
}
catch (Exception ex)
{
Lang.rethrow(ex);
}
return null;
}
项目:lams
文件:DigestAuthenticationMechanism.java
private boolean validateRequest(final DigestContext context, final byte[] ha1) {
byte[] ha2;
DigestQop qop = context.getQop();
// Step 2.2 Calculate H(A2)
if (qop == null || qop.equals(DigestQop.AUTH)) {
ha2 = createHA2Auth(context, context.getParsedHeader());
} else {
ha2 = createHA2AuthInt();
}
byte[] requestDigest;
if (qop == null) {
requestDigest = createRFC2069RequestDigest(ha1, ha2, context);
} else {
requestDigest = createRFC2617RequestDigest(ha1, ha2, context);
}
byte[] providedResponse = context.getParsedHeader().get(DigestAuthorizationToken.RESPONSE).getBytes(UTF_8);
return MessageDigest.isEqual(requestDigest, providedResponse);
}
项目:AppCoins-ethereumj
文件:TreeChunker.java
public TreeChunker(int branches, MessageDigest hasher) {
this.branches = branches;
this.hasher = hasher;
hashSize = hasher.getDigestLength();
chunkSize = hashSize * branches;
}
项目:OpenJSharp
文件:Main.java
/** Display the location and checksum of a class. */
void showClass(String className) {
PrintWriter pw = log.getWriter(WriterKind.NOTICE);
pw.println("javac: show class: " + className);
URL url = getClass().getResource('/' + className.replace('.', '/') + ".class");
if (url == null)
pw.println(" class not found");
else {
pw.println(" " + url);
try {
final String algorithm = "MD5";
byte[] digest;
MessageDigest md = MessageDigest.getInstance(algorithm);
DigestInputStream in = new DigestInputStream(url.openStream(), md);
try {
byte[] buf = new byte[8192];
int n;
do { n = in.read(buf); } while (n > 0);
digest = md.digest();
} finally {
in.close();
}
StringBuilder sb = new StringBuilder();
for (byte b: digest)
sb.append(String.format("%02x", b));
pw.println(" " + algorithm + " checksum: " + sb);
} catch (Exception e) {
pw.println(" cannot compute digest: " + e);
}
}
}
项目:GifImageLoader
文件:Md5FileNameGenerator.java
private byte[] getMD5(byte[] data) {
byte[] hash = null;
try {
MessageDigest digest = MessageDigest.getInstance(HASH_ALGORITHM);
digest.update(data);
hash = digest.digest();
} catch (NoSuchAlgorithmException e) {
L.e(e);
}
return hash;
}
项目:lams
文件:NTLMEngineImpl.java
/**
* Calculates the NTLM2 Session Response for the given challenge, using the
* specified password and client challenge.
*
* @param password
* The user's password.
* @param challenge
* The Type 2 challenge from the server.
* @param clientChallenge
* The random 8-byte client challenge.
*
* @return The NTLM2 Session Response. This is placed in the NTLM response
* field of the Type 3 message; the LM response field contains the
* client challenge, null-padded to 24 bytes.
*/
static byte[] getNTLM2SessionResponse(String password, byte[] challenge,
byte[] clientChallenge) throws NTLMEngineException {
try {
byte[] ntlmHash = ntlmHash(password);
// Look up MD5 algorithm (was necessary on jdk 1.4.2)
// This used to be needed, but java 1.5.0_07 includes the MD5
// algorithm (finally)
// Class x = Class.forName("gnu.crypto.hash.MD5");
// Method updateMethod = x.getMethod("update",new
// Class[]{byte[].class});
// Method digestMethod = x.getMethod("digest",new Class[0]);
// Object mdInstance = x.newInstance();
// updateMethod.invoke(mdInstance,new Object[]{challenge});
// updateMethod.invoke(mdInstance,new Object[]{clientChallenge});
// byte[] digest = (byte[])digestMethod.invoke(mdInstance,new
// Object[0]);
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(challenge);
md5.update(clientChallenge);
byte[] digest = md5.digest();
byte[] sessionHash = new byte[8];
System.arraycopy(digest, 0, sessionHash, 0, 8);
return lmResponse(ntlmHash, sessionHash);
} catch (Exception e) {
if (e instanceof NTLMEngineException)
throw (NTLMEngineException) e;
throw new NTLMEngineException(e.getMessage(), e);
}
}
项目:security-karate
文件:HashingService.java
@Autowired
public HashingService(@Value("${karate.hashing.pepper}") String pepperValue) {
try {
pepper = pepperValue;
salt = getSalt();
digest = MessageDigest.getInstance("SHA-256");
ensureInitOfPepper();
} catch (Exception e) {
//Wrap Exception into RuntimeException...
throw new IllegalStateException("HashingService not correctly intialized!", e);
}
}
项目:javaide
文件:JKS.java
private static byte[] encryptKey(Key key, byte[] passwd)
throws KeyStoreException
{
try
{
MessageDigest sha = MessageDigest.getInstance("SHA1");
SecureRandom rand = SecureRandom.getInstance("SHA1PRNG");
byte[] k = key.getEncoded();
byte[] encrypted = new byte[k.length + 40];
byte[] keystream = rand.getSeed(20);
System.arraycopy(keystream, 0, encrypted, 0, 20);
int count = 0;
while (count < k.length)
{
sha.reset();
sha.update(passwd);
sha.update(keystream);
sha.digest(keystream, 0, keystream.length);
for (int i = 0; i < keystream.length && count < k.length; i++)
{
encrypted[count+20] = (byte) (keystream[i] ^ k[count]);
count++;
}
}
sha.reset();
sha.update(passwd);
sha.update(k);
sha.digest(encrypted, encrypted.length - 20, 20);
// 1.3.6.1.4.1.42.2.17.1.1 is Sun's private OID for this
// encryption algorithm.
return new EncryptedPrivateKeyInfo("1.3.6.1.4.1.42.2.17.1.1",
encrypted).getEncoded();
}
catch (Exception x)
{
throw new KeyStoreException(x.getMessage());
}
}
项目:EyeShopping
文件:PackageManagerUtils.java
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;
}
}
项目:messages-java-sdk
文件:TestHelper.java
/**
* Get SHA1 hash of a string
* @param convertme The string to convert
* @return SHA1 hash
*/
public static String toSHA1(String convertme)
{
byte[] data = convertme.getBytes();
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA-1");
}
catch(NoSuchAlgorithmException e) {
e.printStackTrace();
}
return byteArrayToHexString(md.digest(data));
}
项目:minlia-iot
文件:StringSignatureEncodeHelper.java
public static String md5(String str, String charset) throws Exception {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(str.getBytes(charset));
byte[] result = md.digest();
StringBuffer sb = new StringBuffer(32);
for (int i = 0; i < result.length; i++) {
int val = result[i] & 0xff;
if (val <= 0xf) {
sb.append("0");
}
sb.append(Integer.toHexString(val));
}
return sb.toString().toLowerCase();
}
项目:sstable-adaptor
文件:FBUtilities.java
public static void updateWithInt(MessageDigest digest, int val)
{
digest.update((byte) ((val >>> 24) & 0xFF));
digest.update((byte) ((val >>> 16) & 0xFF));
digest.update((byte) ((val >>> 8) & 0xFF));
digest.update((byte) ((val >>> 0) & 0xFF));
}
项目:OpenVertretung
文件:DigestAuthentication.java
/**
* MD5 version of the "H()" function from rfc2617.
*/
private static String checksumMD5(String data) {
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException ex) {
throw new RuntimeException("Unable to create MD5 instance", ex);
}
// TODO encoding
return hexEncode(md5.digest(data.getBytes()));
}
项目:IJPay
文件:SecureUtil.java
/**
* sha1计算.
*
* @param datas
* 待计算的数据
* @return 计算结果
*/
private static byte[] sha1(byte[] data) {
MessageDigest md = null;
try {
md = MessageDigest.getInstance(ALGORITHM_SHA1);
md.reset();
md.update(data);
return md.digest();
} catch (Exception e) {
LogUtil.writeErrorLog("SHA1计算失败", e);
return null;
}
}
项目:ss-java
文件:EncryptUtils.java
/**
* ShadowSocks's variant of OpenSSL's EVP_BytesToKey(), only one iteration with md5
* digest algorithm and discard the generated iv.
*
* @param password password
* @param keyLength the secret key's length
* @return bytes containing the generated key.
*
* @see <a href="https://github.com/shadowsocks/shadowsocks/blob/06b028b5c08c80931482327eccfb6abf1b2ff15c/shadowsocks/cryptor.py">shadowsocks cryptor.py</a>
* @see <a href="https://wiki.openssl.org/index.php/Manual:EVP_BytesToKey(3)">openssl wiki</a>
*/
public static byte[] EVPBytesToKey(String password, int keyLength) {
MessageDigest md5;
byte[] data;
try {
data = password.getBytes("UTF-8");
md5 = MessageDigest.getInstance("MD5");
} catch (UnsupportedEncodingException | NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
byte[] key = new byte[keyLength];
byte[] m = EMPTY;
int index = 0;
int size;
do {
md5.update(m);
md5.update(data);
m = md5.digest();
size = Math.min(md5.getDigestLength(), keyLength - index);
System.arraycopy(m, 0, key, index, size);
index += size;
} while (index < keyLength);
return key;
}