Java Code Examples for java.security.MessageDigest#digest()

The following examples show how to use java.security.MessageDigest#digest() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BasicAuth.java    From osiris with Apache License 2.0 6 votes vote down vote up
private String decryptPass() throws Exception {
	 
    String secretKey = "osirisSecurity"; 
    String base64EncryptedString = "";

    try {
        byte[] message = Base64.decodeBase64(password.getBytes("utf-8"));
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        byte[] digestOfPassword = md.digest(secretKey.getBytes("utf-8"));
        byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
        SecretKey key = new SecretKeySpec(keyBytes, "DESede");

        Cipher decipher = Cipher.getInstance("DESede");
        decipher.init(Cipher.DECRYPT_MODE, key);

        byte[] plainText = decipher.doFinal(message);

        base64EncryptedString = new String(plainText, "UTF-8");

    } catch (Exception ex) {
    }
    return base64EncryptedString;
}
 
Example 2
Source File: ReinitDigest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void main(Provider p) throws Exception {
    if (p.getService("MessageDigest", "MD5") == null) {
        System.out.println("Provider does not support MD5, skipping");
        return;
    }
    Random r = new Random();
    byte[] data1 = new byte[10 * 1024];
    byte[] data2 = new byte[10 * 1024];
    r.nextBytes(data1);
    r.nextBytes(data2);
    MessageDigest md;
    md = MessageDigest.getInstance("MD5", "SUN");
    byte[] d1 = md.digest(data1);
    md = MessageDigest.getInstance("MD5", p);
    byte[] d2 = md.digest(data1);
    check(d1, d2);
    byte[] d3 = md.digest(data1);
    check(d1, d3);
    md.update(data2);
    md.update((byte)0);
    md.reset();
    byte[] d4 = md.digest(data1);
    check(d1, d4);
    System.out.println("All tests passed");
}
 
Example 3
Source File: Hasher.java    From PortEx with Apache License 2.0 6 votes vote down vote up
/**
 * Computes the hash value for the file bytes from offset <code>from</code>
 * until offset <code>until</code>, using the hash instance as defined by
 * the hash type.
 * 
 * @param file
 *            the file to compute the hash from
 * @param digest
 *            the message digest instance
 * @param from
 *            file offset to start from
 * @param until
 *            file offset for the end
 * @return hash value as byte array
 * @throws IOException
 */
public static byte[] computeHash(File file, MessageDigest digest,
        long from, long until) throws IOException {
    Preconditions.checkArgument(from >= 0, "negative offset");
    Preconditions.checkArgument(until > from, "end offset is smaller or equal to start offset");
    Preconditions.checkArgument(until <= file.length(), "end offset is greater than file length");
    try (RandomAccessFile raf = new RandomAccessFile(file, "r")) {
        byte[] buffer = new byte[BUFFER_SIZE];
        int readbytes;
        long byteSum = from;
        raf.seek(from);
        while ((readbytes = raf.read(buffer)) != -1 && byteSum <= until) {
            byteSum += readbytes;
            if (byteSum > until) {
                readbytes -= (byteSum - until);
            }
            digest.update(buffer, 0, readbytes);
        }
        return digest.digest();
    }
}
 
Example 4
Source File: KeyIdentifier.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a KeyIdentifier from a public-key value.
 *
 * <p>From RFC 5280: Two common methods for generating key identifiers from
 * the public key are:
 * <ol>
 * <li>The keyIdentifier is composed of the 160-bit SHA-1 hash of the
 * value of the BIT STRING subjectPublicKey (excluding the tag,
 * length, and number of unused bits).
 *
 * <li>The keyIdentifier is composed of a four bit type field with
 * the value 0100 followed by the least significant 60 bits of the
 * SHA-1 hash of the value of the BIT STRING subjectPublicKey.
 * </ol>
 * <p>This method supports method 1.
 *
 * @param pubKey the public key from which to construct this KeyIdentifier
 * @throws IOException on parsing errors
 */
public KeyIdentifier(PublicKey pubKey)
    throws IOException
{
    DerValue algAndKey = new DerValue(pubKey.getEncoded());
    if (algAndKey.tag != DerValue.tag_Sequence)
        throw new IOException("PublicKey value is not a valid "
                              + "X.509 public key");

    AlgorithmId algid = AlgorithmId.parse(algAndKey.data.getDerValue());
    byte[] key = algAndKey.data.getUnalignedBitString().toByteArray();

    MessageDigest md = null;
    try {
        md = MessageDigest.getInstance("SHA1");
    } catch (NoSuchAlgorithmException e3) {
        throw new IOException("SHA1 not supported");
    }
    md.update(key);
    this.octetString = md.digest();
}
 
Example 5
Source File: KeyIdentifier.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a KeyIdentifier from a public-key value.
 *
 * <p>From RFC2459: Two common methods for generating key identifiers from
 * the public key are:
 * <ol>
 * <li>The keyIdentifier is composed of the 160-bit SHA-1 hash of the
 * value of the BIT STRING subjectPublicKey (excluding the tag,
 * length, and number of unused bits).
 * <p>
 * <li>The keyIdentifier is composed of a four bit type field with
 * the value 0100 followed by the least significant 60 bits of the
 * SHA-1 hash of the value of the BIT STRING subjectPublicKey.
 * </ol>
 * <p>This method supports method 1.
 *
 * @param pubKey the public key from which to construct this KeyIdentifier
 * @throws IOException on parsing errors
 */
public KeyIdentifier(PublicKey pubKey)
    throws IOException
{
    DerValue algAndKey = new DerValue(pubKey.getEncoded());
    if (algAndKey.tag != DerValue.tag_Sequence)
        throw new IOException("PublicKey value is not a valid "
                              + "X.509 public key");

    AlgorithmId algid = AlgorithmId.parse(algAndKey.data.getDerValue());
    byte[] key = algAndKey.data.getUnalignedBitString().toByteArray();

    MessageDigest md = null;
    try {
        md = MessageDigest.getInstance("SHA1");
    } catch (NoSuchAlgorithmException e3) {
        throw new IOException("SHA1 not supported");
    }
    md.update(key);
    this.octetString = md.digest();
}
 
Example 6
Source File: Md5FileNameGenerator.java    From MiBandDecompiled with Apache License 2.0 6 votes vote down vote up
private byte[] a(byte abyte0[])
{
    byte abyte1[];
    try
    {
        MessageDigest messagedigest = MessageDigest.getInstance("MD5");
        messagedigest.update(abyte0);
        abyte1 = messagedigest.digest();
    }
    catch (NoSuchAlgorithmException nosuchalgorithmexception)
    {
        L.e(nosuchalgorithmexception);
        return null;
    }
    return abyte1;
}
 
Example 7
Source File: Encryption.java    From NoHttp with Apache License 2.0 6 votes vote down vote up
/**
 * Get the MD5 value of string.
 *
 * @param content the target string.
 * @return the MD5 value.
 */
public static String getMD5ForString(String content) {
    StringBuilder md5Buffer = new StringBuilder();
    try {
        MessageDigest digest = MessageDigest.getInstance("MD5");
        byte[] tempBytes = digest.digest(content.getBytes());
        int digital;
        for (int i = 0; i < tempBytes.length; i++) {
            digital = tempBytes[i];
            if (digital < 0) {
                digital += 256;
            }
            if (digital < 16) {
                md5Buffer.append("0");
            }
            md5Buffer.append(Integer.toHexString(digital));
        }
    } catch (NoSuchAlgorithmException e) {
        Logger.e(e);
    }
    return md5Buffer.toString();
}
 
Example 8
Source File: KdbxCreds.java    From KeePassJava2 with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor for password with  KDBX Keyfile
 * @param password Master Password (<code>new byte[0]</code> if empty, not none)
 * @param inputStream inputstream of the keyfile
 */
public KdbxCreds(@NotNull byte[] password, @NotNull InputStream inputStream) {
    MessageDigest md = Encryption.getMessageDigestInstance();
    byte[] pwKey = md.digest(password);
    md.update(pwKey);

    byte[] keyFileData = KdbxKeyFile.load(inputStream);
    if (keyFileData == null) {
        throw new IllegalStateException("Could not read key file");
    }
    this.key = md.digest(keyFileData);
}
 
Example 9
Source File: TableEncryptor.java    From SmartProxy with GNU General Public License v3.0 5 votes vote down vote up
long passwordToInt64(String password){
	try {
		byte[] passwordBytes=password.getBytes("UTF-8");
		MessageDigest md5 = MessageDigest.getInstance("MD5"); 
		byte[] hashPwd=md5.digest(passwordBytes);
		long a = bytesToInt64(hashPwd);
		return a;
	} catch (Exception e) {
		e.printStackTrace();
		return 0;
	}
}
 
Example 10
Source File: TextUtils.java    From SendBird-Android with MIT License 5 votes vote down vote up
/**
 * Calculate MD5
 * @param data
 * @return
 * @throws NoSuchAlgorithmException
 */
public static String generateMD5(String data) throws NoSuchAlgorithmException {
    MessageDigest digest = MessageDigest.getInstance("MD5");
    digest.update(data.getBytes());
    byte messageDigest[] = digest.digest();

    StringBuffer hexString = new StringBuffer();
    for (int i = 0; i < messageDigest.length; i++)
        hexString.append(Integer.toHexString(0xFF & messageDigest[i]));

    return hexString.toString();
}
 
Example 11
Source File: Attachment.java    From TinCanJava with Apache License 2.0 5 votes vote down vote up
public void setContent(byte[] content) throws NoSuchAlgorithmException {
    this.content = Arrays.copyOf(content, content.length);
    this.setLength(content.length);
    MessageDigest digest = MessageDigest.getInstance("SHA-256");
    digest.update(content);
    byte[] hash = digest.digest();
    this.setSha2(new String(Hex.encodeHex(hash)));
}
 
Example 12
Source File: Util.java    From youkefu with Apache License 2.0 5 votes vote down vote up
/**
 * Parses a string and returns a SHA-256 checksum of it.
 *
 * @param value The source string to parse.
 * @return A checksum of the source string.
 */
public static byte[] digestSha256(String value) {
    final MessageDigest algorithm;
    try {
        algorithm = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
    return algorithm.digest(value.getBytes());
}
 
Example 13
Source File: DigestUtilTest.java    From snowblossom with Apache License 2.0 5 votes vote down vote up
private ChainHash treeHash(ChainHash a, ChainHash b)
{
  MessageDigest md = DigestUtil.getMD();
  md.update(a.toByteArray());
  md.update(b.toByteArray());

  ChainHash r = new ChainHash(md.digest());

  System.out.println("" +a + " + " + b + " -> " + r);

  return r;
}
 
Example 14
Source File: Hash.java    From token-core-android with Apache License 2.0 5 votes vote down vote up
private static byte[] sha256(byte[] input, int offset, int length) {
  try {
    MessageDigest md = MessageDigest.getInstance("SHA-256");
    md.update(input, offset, length);
    return md.digest();
  } catch (Exception ex) {
    throw new TokenException(Messages.WALLET_SHA256);
  }
}
 
Example 15
Source File: GXSecure.java    From gurux.dlms.java with GNU General Public License v2.0 5 votes vote down vote up
private static SecretKeySpec getKey(byte[] pass)
        throws NoSuchAlgorithmException {
    final MessageDigest sha = MessageDigest.getInstance("SHA-256");

    byte[] key = sha.digest(pass);
    // use only first 128 bit (16 bytes). By default Java only supports AES
    // 128 bit key sizes for encryption.
    // Updated jvm policies are required for 256 bit.
    key = Arrays.copyOf(key, 16);
    return new SecretKeySpec(key, "AES");
}
 
Example 16
Source File: SrpUser.java    From xbee-java with Mozilla Public License 2.0 4 votes vote down vote up
/**
 * Returns M1 if the challenge was successfully processed.
 *
 * @param byte_s Salt.
 * @param byte_B Public ephemeral value B.
 *
 * @return Proof of session key M1, or {@code null} if the challenge could
 *         not be processed.
 * 
 * @throws IOException If there is a problem generating any value.
 * @throws NoSuchAlgorithmException If the hash algorithm to use does not
 *                                  exist.
 */
public byte[] processChallenge(byte[] byte_s, byte[] byte_B) throws NoSuchAlgorithmException, IOException {
	BigInteger B = SrpUtils.bigIntegerFromBytes(byte_B);

	// SRP-6a dictated safety check.
	if (B.mod(N).equals(BigInteger.ZERO))
		return null;

	// Compute M.
	byte[] byte_M;

	MessageDigest digest = MessageDigest.getInstance(SrpConstants.HASH_ALGORITHM);
	ByteArrayOutputStream os = new ByteArrayOutputStream();
	os.write(byte_A);
	os.write(SrpUtils.bigIntegerToBytes(B));
	byte[] byte_u = digest.digest(os.toByteArray());

	BigInteger u = SrpUtils.bigIntegerFromBytes(byte_u);

	// SRP-6a dictated safety check.
	if (u.equals(BigInteger.ZERO))
		return null;

	// Compute x.
	byte[] byte_I = username.getBytes();
	byte[] byte_p = password.getBytes();
	byte[] byte_x = SrpUtils.generateX(byte_s, byte_I, byte_p);
	BigInteger x = SrpUtils.bigIntegerFromBytes(byte_x);

	// Compute v.
	BigInteger v = g.modPow(x, N).abs();

	// Compute S.
	// The remainder is computed here, not the modulo.
	// This means that, if n is negative, we need to do N - remainder to get the modulo.
	BigInteger S = B.subtract(k.multiply(v)).modPow(a.add(u.multiply(x)), N);

	if (S.compareTo(BigInteger.ZERO) < 0)
		S = N.add(S);

	// Compute K.
	byte_K = digest.digest(SrpUtils.bigIntegerToBytes(S));

	// Compute M.
	byte_M = SrpUtils.generateM(SrpUtils.bigIntegerToBytes(N), SrpUtils.bigIntegerToBytes(g), byte_I,
			byte_s, byte_A, SrpUtils.bigIntegerToBytes(B), byte_K);

	// And finally, hash A, M and K together.
	os = new ByteArrayOutputStream();
	os.write(byte_A);
	os.write(byte_M);
	os.write(byte_K);
	H_AMK = digest.digest(os.toByteArray());

	return byte_M;
}
 
Example 17
Source File: StringUtils.java    From springreplugin with Apache License 2.0 4 votes vote down vote up
public static final String md5base64(byte buffer[]) throws NoSuchAlgorithmException {
    MessageDigest digest = MessageDigest.getInstance("MD5");
    digest.update(buffer);
    byte buf2[] = digest.digest();
    return Base64.encodeToString(buf2, Base64.NO_WRAP | Base64.NO_PADDING | Base64.NO_CLOSE);
}
 
Example 18
Source File: DLeftCountingBloomFilterTest.java    From streaminer with Apache License 2.0 4 votes vote down vote up
@Test
public void test() throws NoSuchAlgorithmException {
    MessageDigest md = MessageDigest.getInstance("SHA-1");
    
    byte[] b = md.digest("testf".getBytes());
    
    String hex = byteArrayToHexString(b);
    
    System.out.println("Byte size: " + b.length);
    System.out.println("Hex: " + hex);
    
    DLeftCountingBloomFilter filter = new DLeftCountingBloomFilter(8, 32);
    
    long bits = filter.getBits(b, 5, 0);
    System.out.println("Bits: " + bits);
}
 
Example 19
Source File: Sha256Hash.java    From guarda-android-wallets with GNU General Public License v3.0 4 votes vote down vote up
public static byte[] hash(byte[] input, int offset, int length) {
  MessageDigest digest = newDigest();
  digest.update(input, offset, length);
  return digest.digest();
}
 
Example 20
Source File: ShaEncoder.java    From entando-components with GNU Lesser General Public License v3.0 3 votes vote down vote up
public static String encodePassword(String password) throws NoSuchAlgorithmException {

		if (password != null) {

			MessageDigest digest = MessageDigest.getInstance("SHA");

			digest.update(password.getBytes());

			byte bytes[] = digest.digest();

			StringBuilder buffer = new StringBuilder();

			for (int i = 0; i < bytes.length; i++) {

				int b = bytes[i] & 0xff;

				if (b < 16) {

					buffer.append("0");

				}

				buffer.append(Integer.toHexString(b));

			}

			password = buffer.toString();

		}

		return password;

	}