All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.rcll.llsf_comm.KeyConverter Maven / Gradle / Ivy

There is a newer version: 0.1.19.1
Show newest version
package com.rcll.llsf_comm;

import java.security.MessageDigest;

/**
 * This class converts the encryption key given as a String into a key that can be
 * used by the algorithm. Besides it creates the first initialization vector.
 *
 */
class KeyConverter {

	/**
	 * Thanks go to Ola Bini for releasing this source on his blog. The source was obtained from
	 * here.
	 */
	public static byte[][] EVP_BytesToKey(int key_len, int iv_len,
			MessageDigest md, byte[] salt, byte[] data, int count) {
		byte[][] both = new byte[2][];
		byte[] key = new byte[key_len];
		int key_ix = 0;
		byte[] iv = new byte[iv_len];
		int iv_ix = 0;
		both[0] = key;
		both[1] = iv;
		byte[] md_buf = null;
		int nkey = key_len;
		int niv = iv_len;
		int i = 0;
		if (data == null) {
			return both;
		}
		int addmd = 0;
		for (;;) {
			md.reset();
			if (addmd++ > 0) {
				md.update(md_buf);
			}
			md.update(data);
			if (null != salt) {
				md.update(salt, 0, 8);
			}
			md_buf = md.digest();
			for (i = 1; i < count; i++) {
				md.reset();
				md.update(md_buf);
				md_buf = md.digest();
			}
			i = 0;
			if (nkey > 0) {
				for (;;) {
					if (nkey == 0)
						break;
					if (i == md_buf.length)
						break;
					key[key_ix++] = md_buf[i];
					nkey--;
					i++;
				}
			}
			if (niv > 0 && i != md_buf.length) {
				for (;;) {
					if (niv == 0)
						break;
					if (i == md_buf.length)
						break;
					iv[iv_ix++] = md_buf[i];
					niv--;
					i++;
				}
			}
			if (nkey == 0 && niv == 0) {
				break;
			}
		}
		for (i = 0; i < md_buf.length; i++) {
			md_buf[i] = 0;
		}
		return both;
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy