org.junit.jupiter.params.provider.EnumSource#java.security.MessageDigest源码实例Demo

下面列出了org.junit.jupiter.params.provider.EnumSource#java.security.MessageDigest 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: das   文件: MD5Util.java
public static String parseStrToMd5L32(String str) {
    String reStr = null;
    try {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        byte[] bytes = md5.digest(str.getBytes());
        StringBuffer stringBuffer = new StringBuffer();
        for (byte b : bytes) {
            int bt = b & 0xff;
            if (bt < 16) {
                stringBuffer.append(0);
            }
            stringBuffer.append(Integer.toHexString(bt));
        }
        reStr = stringBuffer.toString();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return reStr;
}
 
源代码2 项目: KJFrameForAndroid   文件: SystemTool.java
/**
 * 将签名字符串转换成需要的32位签名
 */
private static String hexdigest(byte[] paramArrayOfByte) {
    final char[] hexDigits = { 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 97,
            98, 99, 100, 101, 102 };
    try {
        MessageDigest localMessageDigest = MessageDigest.getInstance("MD5");
        localMessageDigest.update(paramArrayOfByte);
        byte[] arrayOfByte = localMessageDigest.digest();
        char[] arrayOfChar = new char[32];
        for (int i = 0, j = 0;; i++, j++) {
            if (i >= 16) {
                return new String(arrayOfChar);
            }
            int k = arrayOfByte[i];
            arrayOfChar[j] = hexDigits[(0xF & k >>> 4)];
            arrayOfChar[++j] = hexDigits[(k & 0xF)];
        }
    } catch (Exception e) {
    }
    return "";
}
 
源代码3 项目: moleculer-java   文件: ShardStrategyFactory.java
@Override
public Long apply(String key) {
	byte[] bytes = key.getBytes(StandardCharsets.UTF_8);
	MessageDigest hasher = hashers.get();
	if (hasher == null) {
		try {
			hasher = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException notFound) {
			throw new RuntimeException(notFound);
		}
		hashers.set(hasher);
	}
	hasher.update(bytes);
	byte[] md5Bytes = hasher.digest();
	char[] hexChars = new char[md5Bytes.length * 2];
	for (int j = 0; j < md5Bytes.length; j++) {
		int v = md5Bytes[j] & 0xFF;
		hexChars[j * 2] = HEX[v >>> 4];
		hexChars[j * 2 + 1] = HEX[v & 0x0F];
	}
	String hexString = new String(hexChars);
	if (hexString.length() > 8) {
		hexString = hexString.substring(0, 8);
	}
	return Long.parseLong(hexString, 16);
}
 
源代码4 项目: projectforge-webapp   文件: Crypt.java
private static String encode(final String s, final String alg)
{
  try {
    final MessageDigest md = MessageDigest.getInstance(alg);
    md.reset();
    md.update(s.getBytes());
    final byte[] d = md.digest();

    String ret = "";

    for (int val : d) {
      final char[] hex = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
      if (val < 0) {
        val = 256 + val;
      }
      final char hi = hex[val / 16];
      final char lo = hex[val % 16];
      ret = hi + "" + lo + ret;
    }
    return md.getAlgorithm() + '{' + ret + '}';
  } catch (final NoSuchAlgorithmException ex) {
    log.fatal(ex);
    return "NONE{" + s + "}";
  }
}
 
源代码5 项目: TelegramApi   文件: CryptoUtils.java
public static String MD5(RandomAccessFile randomAccessFile) {
    try {
        MessageDigest crypt = md5.get();
        crypt.reset();
        byte[] block = new byte[8 * 1024];
        for (int i = 0; i < randomAccessFile.length(); i += 8 * 1024) {
            int len = (int) Math.min(block.length, randomAccessFile.length() - i);
            randomAccessFile.readFully(block, 0, len);
            crypt.update(block, 0, len);
        }
        return ToHex(crypt.digest());
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}
 
源代码6 项目: fdb-record-layer   文件: ResolverMappingDigest.java
private CompletableFuture<byte[]> computeInternal(@Nonnull FDBRecordContext context,
                                                  @Nullable byte[] continuation,
                                                  @Nonnull MessageDigest messageDigest) {

    return resolver.getMappingSubspaceAsync().thenCompose(mappingSubspace -> {
        final RecordCursor<KeyValue> cursor = KeyValueCursor.Builder.withSubspace(mappingSubspace)
                .setScanProperties(new ScanProperties(ExecuteProperties.newBuilder().setReturnedRowLimit(transactionRowLimit).setIsolationLevel(IsolationLevel.SNAPSHOT).build()))
                .setContext(context)
                .setContinuation(continuation)
                .build();

        return cursor.forEachResult(result -> {
            KeyValue kv = result.get();
            String key = mappingSubspace.unpack(kv.getKey()).getString(0);
            ResolverResult value = resolver.deserializeValue(kv.getValue());

            messageDigest.update(Tuple.from(key, value.getValue(), value.getMetadata()).pack());
        }).thenApply(result -> result.getContinuation().toBytes());
    });
}
 
源代码7 项目: PressureNet   文件: BarometerNetworkActivity.java
/**
 * Get a unique ID by fetching the phone ID and hashing it
 * 
 * @return
 */
private String getID() {
	try {
		MessageDigest md = MessageDigest.getInstance("MD5");

		String actual_id = Secure.getString(getApplicationContext()
				.getContentResolver(), Secure.ANDROID_ID);
		byte[] bytes = actual_id.getBytes();
		byte[] digest = md.digest(bytes);
		StringBuffer hexString = new StringBuffer();
		for (int i = 0; i < digest.length; i++) {
			hexString.append(Integer.toHexString(0xFF & digest[i]));
		}
		return hexString.toString();
	} catch (Exception e) {
		return "--";
	}
}
 
源代码8 项目: netty-restful-server   文件: MessageDigestUtil.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 {
        byte[] btInput = s.getBytes();
        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;
    }
}
 
源代码9 项目: uyuni   文件: MD5Crypt.java
/**
 * MD5 and Hexify an array of bytes.  Take the input array, MD5 encodes it
 * and then turns it into Hex.
 * @param secretBytes you want md5hexed
 * @return md5hexed String.
 */
public static String md5Hex(byte[] secretBytes) {
    String retval = null;
    // add secret
    MessageDigest md;
    try {
        md = MessageDigest.getInstance("MD5");
        //byte[] secretBytes = inputString.getBytes("UTF-8");
        md.update(secretBytes);
        // generate the digest
        byte[] digest = md.digest();
        // hexify this puppy
        retval = new String(Hex.encodeHex(digest));
    }
    catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("NoSuchAlgorithm: MD5.  Something" +
                " weird with your JVM, you should be able to do this.", e);
    }
    return retval;
}
 
private String encode(String src, char[] passwd, MessageDigest md) {
    try {
        md.update(src.getBytes("ISO-8859-1"));
    } catch (java.io.UnsupportedEncodingException uee) {
        assert false;
    }
    if (passwd != null) {
        byte[] passwdBytes = new byte[passwd.length];
        for (int i=0; i<passwd.length; i++)
            passwdBytes[i] = (byte)passwd[i];
        md.update(passwdBytes);
        Arrays.fill(passwdBytes, (byte)0x00);
    }
    byte[] digest = md.digest();

    StringBuffer res = new StringBuffer(digest.length * 2);
    for (int i = 0; i < digest.length; i++) {
        int hashchar = ((digest[i] >>> 4) & 0xf);
        res.append(charArray[hashchar]);
        hashchar = (digest[i] & 0xf);
        res.append(charArray[hashchar]);
    }
    return res.toString();
}
 
源代码11 项目: YTPlayer   文件: FileUtils.java
public static String SHA1(InputStream is) {
    try {
        MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
        final byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        for (int read; (read = is.read(buffer)) != -1; ) {
            messageDigest.update(buffer, 0, read);
        }

        Formatter formatter = new Formatter();
        // Convert the byte to hex format
        for (final byte b : messageDigest.digest()) {
            formatter.format("%02x", b);
        }
        return formatter.toString();
    } catch (NoSuchAlgorithmException | IOException e) {
        android.util.Log.e(TAG,e.getMessage());
    } finally {
        YTutils.close(is);
    }
    return null;
}
 
源代码12 项目: openjdk-jdk8u-backup   文件: DESKey.java
public boolean equals(Object obj) {
    if (this == obj)
        return true;

    if (!(obj instanceof SecretKey))
        return false;

    String thatAlg = ((SecretKey)obj).getAlgorithm();
    if (!(thatAlg.equalsIgnoreCase("DES")))
        return false;

    byte[] thatKey = ((SecretKey)obj).getEncoded();
    boolean ret = MessageDigest.isEqual(this.key, thatKey);
    java.util.Arrays.fill(thatKey, (byte)0x00);
    return ret;
}
 
源代码13 项目: 12306XposedPlugin   文件: Md5Util.java
public static String encrypt(String string) {
    if (TextUtils.isEmpty(string)) {
        return "";
    }
    MessageDigest md5;
    try {
        md5 = MessageDigest.getInstance("MD5");
        byte[] bytes = md5.digest(string.getBytes());
        StringBuilder result = new StringBuilder();
        for (byte b : bytes) {
            String temp = Integer.toHexString(b & 0xff);
            if (temp.length() == 1) {
                temp = "0" + temp;
            }
            result.append(temp);
        }
        return result.toString();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return "";
}
 
源代码14 项目: ranger   文件: RangerKeyStore.java
private MessageDigest getKeyedMessageDigest(char[] aKeyPassword)
        throws NoSuchAlgorithmException, UnsupportedEncodingException {
    int i, j;

    MessageDigest md = MessageDigest.getInstance("SHA");
    byte[] keyPasswordBytes = new byte[aKeyPassword.length * 2];
    for (i = 0, j = 0; i < aKeyPassword.length; i++) {
        keyPasswordBytes[j++] = (byte) (aKeyPassword[i] >> 8);
        keyPasswordBytes[j++] = (byte) aKeyPassword[i];
    }
    md.update(keyPasswordBytes);
    for (i = 0; i < keyPasswordBytes.length; i++)
        keyPasswordBytes[i] = 0;
    md.update(SECRET_KEY_HASH_WORD.getBytes("UTF8"));
    return md;
}
 
源代码15 项目: YiZhi   文件: MD5Utils.java
public static String getMD5(String str) {
    MessageDigest md5 = null;
    try {
        md5 = MessageDigest.getInstance("MD5");
    } catch (Exception e) {
        e.printStackTrace();
        return "";
    }
    char[] charArray = str.toCharArray();
    byte[] byteArray = new byte[charArray.length];
    for (int i = 0; i < charArray.length; i++) {
        byteArray[i] = (byte) charArray[i];
    }
    byte[] md5Bytes = md5.digest(byteArray);
    StringBuffer hexValue = new StringBuffer();
    for (int i = 0; i < md5Bytes.length; i++) {
        int val = ((int) md5Bytes[i]) & 0xff;
        if (val < 16) {
            hexValue.append("0");
        }
        hexValue.append(Integer.toHexString(val));
    }
    return hexValue.toString();
}
 
protected String md5sign(final String txId, final String amount) {

        final StringBuilder sign = new StringBuilder();
        sign.append(getParameterValue(AN_MD5_HASH_KEY));
        sign.append(getParameterValue(AN_API_LOGIN_ID));
        sign.append(txId);
        sign.append(amount);
        sign.append("EUR");

        try {
            final Charset charset = StandardCharsets.UTF_8;
            final MessageDigest digest = MessageDigest.getInstance("MD5");
            return new String(Hex.encodeHex(digest.digest(sign.toString().getBytes(charset)))).toUpperCase();
        } catch (NoSuchAlgorithmException e) {
            LOG.error("MD5 not available", e);
            return "MD5 not available";
        }
    }
 
源代码17 项目: saros   文件: XMPPAccountStore.java
public static byte[] encrypt(byte[] data, String key)
    throws NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException,
        InvalidKeyException, IllegalBlockSizeException, BadPaddingException,
        InvalidAlgorithmParameterException {

  Cipher cipher = Cipher.getInstance(TRANSFORMATION);

  MessageDigest digest = MessageDigest.getInstance(MESSAGE_DIGEST_ALGORITHM);
  digest.update(key.getBytes("UTF-8"));

  // default JVM impl. may only support key strength up to 128 bit;
  byte[] keyData = new byte[16];
  System.arraycopy(digest.digest(), 0, keyData, 0, keyData.length);

  SecretKeySpec keySpec = new SecretKeySpec(keyData, SECRET_KEY_ALGORITHM);
  IvParameterSpec ivSpec = new IvParameterSpec(IV);

  data = deflate(data);

  cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);

  return xor(cipher.doFinal(data));
}
 
源代码18 项目: jdk8u-jdk   文件: SignatureFileVerifier.java
/** get digest from cache */

    private MessageDigest getDigest(String algorithm) throws SignatureException {
        // check that algorithm is not restricted
        if (!JAR_DISABLED_CHECK.permits(DIGEST_PRIMITIVE_SET, algorithm, null)) {
            SignatureException e =
                    new SignatureException("SignatureFile check failed. " +
                            "Disabled algorithm used: " + algorithm);
            throw e;
        }

        if (createdDigests == null)
            createdDigests = new HashMap<String, MessageDigest>();

        MessageDigest digest = createdDigests.get(algorithm);

        if (digest == null) {
            try {
                digest = MessageDigest.getInstance(algorithm);
                createdDigests.put(algorithm, digest);
            } catch (NoSuchAlgorithmException nsae) {
                // ignore
            }
        }
        return digest;
    }
 
源代码19 项目: JavaWeb   文件: CoreControllerHelp.java
/**
URL(服务器地址) http://www.programself.com/JavaWeb/app/weichat/core/accessWeiChat
Token(令牌) pirtzxLSjoAjacYXemOSflqtyns0wpQK
EncodingAESKey(消息加解密密钥) xcd4N4i53IB9rrtLOra7Tvt8ybLLhAzjacKhGBaUb7h
消息加解密方式 安全模式
*/

//校验签名
public static boolean checkSignature(String signature, String timestamp, String nonce) throws Exception {
	//将token、timestamp、nonce三个参数进行字典序排序
	String[] paramArr = new String[] { Token, timestamp, nonce };
	Arrays.sort(paramArr);
	//将三个参数字符串拼接成一个字符串进行sha1加密
	String content = paramArr[0].concat(paramArr[1]).concat(paramArr[2]);
	MessageDigest md = MessageDigest.getInstance("SHA-1");
	// 对接后的字符串进行sha1加密
	byte[] digest = md.digest(content.toString().getBytes());
	String ciphertext = byteToStr(digest);
	//开发者获得加密后的字符串可与signature对比,标识该请求来源于微信
	return ciphertext != null ? ciphertext.equals(signature.toUpperCase()) : false;
}
 
源代码20 项目: openjdk-8   文件: MessageToken_v2.java
/**
 * Verifies the validity of checksum field
 *
 * @param data the application data
 * @param offset the offset where the data begins
 * @param len the length of the application data
 *
 * @throws GSSException if an error occurs in the checksum calculation
 */
public final boolean verifySign(byte[] data, int offset, int len)
    throws GSSException {

    // debug("\t====In verifySign:====\n");
    // debug("\t\t checksum:   [" + getHexBytes(checksum) + "]\n");
    // debug("\t\t data = [" + getHexBytes(data) + "]\n");

    byte[] myChecksum = getChecksum(data, offset, len);
    // debug("\t\t mychecksum: [" + getHexBytes(myChecksum) +"]\n");

    if (MessageDigest.isEqual(checksum, myChecksum)) {
        // debug("\t\t====Checksum PASS:====\n");
        return true;
    }
    return false;
}
 
源代码21 项目: box-java-sdk   文件: BoxFileTest.java
private MessageDigest uploadParts(BoxFile uploadedFile, BoxFileUploadSession.Info session,
                                  long fileSize, String fileName) throws Exception {

    URL fileURL = this.getClass().getResource("/sample-files/" + fileName);
    String filePath = URLDecoder.decode(fileURL.getFile(), "utf-8");
    File file = new File(filePath);

    FileInputStream stream = new FileInputStream(file);
    MessageDigest fileDigest = MessageDigest.getInstance("SHA1");
    DigestInputStream dis = new DigestInputStream(stream, fileDigest);

    long offset = 0;
    byte[] bytes = null;
    long processed = 0;
    boolean canBreak = false;
    while (true) {
        long min = session.getPartSize();
        long diff = fileSize - processed;
        if (diff < min) {
            min = diff;
            canBreak = true;
        }

        BoxFileUploadSessionPart part = session.getResource().uploadPart(dis, offset, (int) min, fileSize);
        Assert.assertNotNull(part.getSha1());
        Assert.assertNotNull(part.getPartId());
        Assert.assertEquals(part.getOffset(), offset);
        Assert.assertTrue(part.getSize() <= session.getPartSize());
        offset = offset + session.getPartSize();
        processed += min;
        if (canBreak) {
            break;
        }
    }

    return fileDigest;
}
 
源代码22 项目: Kylin   文件: CubeDesc.java
public String calculateSignature() {
    MessageDigest md = null;
    try {
        md = MessageDigest.getInstance("MD5");
        StringBuilder sigString = new StringBuilder();
        sigString.append(this.name).append("|").append(this.getFactTable()).append("|").append(JsonUtil.writeValueAsString(this.model.getPartitionDesc())).append("|").append(JsonUtil.writeValueAsString(this.dimensions)).append("|").append(JsonUtil.writeValueAsString(this.measures)).append("|").append(JsonUtil.writeValueAsString(this.rowkey)).append("|").append(JsonUtil.writeValueAsString(this.hbaseMapping));

        byte[] signature = md.digest(sigString.toString().getBytes());
        return new String(Base64.encodeBase64(signature));
    } catch (NoSuchAlgorithmException | JsonProcessingException e) {
        throw new RuntimeException("Failed to calculate signature");
    }
}
 
源代码23 项目: openjdk-jdk9   文件: SignatureValidator.java
private boolean digestInputEqual(Reference ref) throws Exception {
    MessageDigest md = MessageDigest.getInstance("SHA1");
    InputStream is = ref.getDigestInputStream();
    int nbytes;
    byte[] buf = new byte[256];
    while ((nbytes = is.read(buf, 0, buf.length)) != -1) {
        md.update(buf, 0, nbytes);
    }
    return Arrays.equals(md.digest(), ref.getDigestValue());
}
 
源代码24 项目: hadoop-ozone   文件: HadoopFsValidator.java
private void validateFile(long counter) throws Exception {
  Path file = new Path(rootPath + "/" + generateObjectName(counter));

  byte[] content = timer.time(() -> {
    try (FSDataInputStream input = fileSystem.open(file)) {
      return IOUtils.toByteArray(input);
    }
  });

  if (!MessageDigest.isEqual(referenceDigest, getDigest(content))) {
    throw new IllegalStateException(
        "Reference (=first) message digest doesn't match with digest of "
            + file.toString());
  }
}
 
源代码25 项目: sakai   文件: PathHashUtil.java
/**
 * create a SHA1 hash of the path
 *
 * @param nodePath
 * @param encode
 * @return some SHA1 hash value possibly
 * @throws NoSuchAlgorithmException
 */
public static String hash(String nodePath)
{
	MessageDigest mdigest  = (MessageDigest) digest.get();
	if ( mdigest == null ) 
	{
		try
		{
			mdigest = MessageDigest.getInstance("SHA1");
            digest.set(mdigest);
		}
		catch (NoSuchAlgorithmException e)
		{
		    throw new RuntimeException("Failed to find SHA1 message digest: " + e, e);
		}
	}
	byte[] b = mdigest.digest(nodePath.getBytes());
	char[] c = new char[b.length * 2];
	for (int i = 0; i < b.length; i++)
	{
		c[i * 2] = encode[b[i]&0x0f];
		c[i * 2 + 1] = encode[(b[i]>>4)&0x0f];
	}
	String encoded =  new String(c);
	log.debug("Encoded "+nodePath+" as "+encoded);
	return encoded;
}
 
源代码26 项目: classchecks   文件: CheckSumBuilder.java
private static String encode(String algorithm, String value) {
    if (value == null) {
        return null;
    }
    try {
        MessageDigest messageDigest
                = MessageDigest.getInstance(algorithm);
        messageDigest.update(value.getBytes());
        return getFormattedText(messageDigest.digest());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
源代码27 项目: kognitivo   文件: Utility.java
private static String hashBytes(MessageDigest hash, byte[] bytes) {
    hash.update(bytes);
    byte[] digest = hash.digest();
    StringBuilder builder = new StringBuilder();
    for (int b : digest) {
        builder.append(Integer.toHexString((b >> 4) & 0xf));
        builder.append(Integer.toHexString((b >> 0) & 0xf));
    }
    return builder.toString();
}
 
源代码28 项目: ezScrum   文件: AccountDAO.java
public String getMd5(String str) {
	MessageDigest md = null;
	try {
		md = MessageDigest.getInstance("MD5");
	} catch (Exception e) {
		e.printStackTrace();
	}
	md.update(str.getBytes());
	byte b[] = md.digest();
	str = byte2hex(b);
	return str;
}
 
源代码29 项目: softservice   文件: MessageDigestUtils.java
public static String encrypt(String password,String algorithm){
	try {
		MessageDigest md = MessageDigest.getInstance(algorithm);
		byte[] b = md.digest(password.getBytes());
		return ByteUtils.byte2HexString(b);
	}catch (Exception e){
		e.printStackTrace();
		return null;
	}
}
 
源代码30 项目: Bytecoder   文件: ManifestDigester.java
/** Netscape doesn't include the new line. Intel and JavaSoft do */

        public byte[] digestWorkaround(MessageDigest md)
        {
            md.reset();
            for (Section sec : sections) {
                md.update(sec.rawBytes, sec.offset, sec.length);
            }
            return md.digest();
        }