org.bouncycastle.crypto.macs.HMac Java Examples

The following examples show how to use org.bouncycastle.crypto.macs.HMac. 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: LibraKeyFactory.java    From jlibra with Apache License 2.0 6 votes vote down vote up
public LibraKeyFactory(Seed seed) {
    byte[] data = new byte[32];
    SHA3Digest sha3 = new SHA3Digest(256);
    HMac mac = new HMac(sha3);
    mac.init(new KeyParameter(MASTER_KEY_SALT));
    mac.update(seed.getData(), 0, seed.getData().length);
    mac.doFinal(data, 0);

    this.master = new Master(data);
}
 
Example #2
Source File: Ed25519PrivateKey.java    From hedera-sdk-java with Apache License 2.0 6 votes vote down vote up
/**
 * Recover a private key from a generated mnemonic phrase and a passphrase.
 * <p>
 * This is not compatible with the phrases generated by the Android and iOS wallets;
 * use the no-passphrase version instead.
 *
 * @param mnemonic   the mnemonic phrase which should be a 24 byte list of words.
 * @param passphrase the passphrase used to protect the mnemonic (not used in the
 *                   mobile wallets, use {@link #fromMnemonic(Mnemonic)} instead.)
 * @return the recovered key; use {@link #derive(int)} to get a key for an account index (0
 * for default account)
 */
public static Ed25519PrivateKey fromMnemonic(Mnemonic mnemonic, String passphrase) {
    final byte[] seed = mnemonic.toSeed(passphrase);

    final HMac hmacSha512 = new HMac(new SHA512Digest());
    hmacSha512.init(new KeyParameter("ed25519 seed".getBytes(StandardCharsets.UTF_8)));
    hmacSha512.update(seed, 0, seed.length);

    final byte[] derivedState = new byte[hmacSha512.getMacSize()];
    hmacSha512.doFinal(derivedState, 0);

    Ed25519PrivateKey derivedKey = derivableKey(derivedState);

    // BIP-44 path with the Hedera Hbar coin-type (omitting key index)
    // we pre-derive most of the path as the mobile wallets don't expose more than the index
    // https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki
    // https://github.com/satoshilabs/slips/blob/master/slip-0044.md
    for (int index : new int[]{44, 3030, 0, 0}) {
        derivedKey = derivedKey.derive(index);
    }

    return derivedKey;
}
 
Example #3
Source File: HmacContentSigner.java    From xipki with Apache License 2.0 6 votes vote down vote up
public HmacContentSigner(HashAlgo hashAlgo, AlgorithmIdentifier algorithmIdentifier,
    SecretKey signingKey) throws XiSecurityException {
  this.algorithmIdentifier = Args.notNull(algorithmIdentifier, "algorithmIdentifier");
  Args.notNull(signingKey, "signingKey");
  try {
    this.encodedAlgorithmIdentifier = algorithmIdentifier.getEncoded();
  } catch (IOException ex) {
    throw new XiSecurityException("could not encode AlgorithmIdentifier", ex);
  }
  if (hashAlgo == null) {
    hashAlgo = AlgorithmUtil.extractHashAlgoFromMacAlg(algorithmIdentifier);
  }

  this.hmac = new HMac(hashAlgo.createDigest());
  byte[] keyBytes = signingKey.getEncoded();
  this.hmac.init(new KeyParameter(keyBytes, 0, keyBytes.length));
  this.outLen = hmac.getMacSize();
  this.outputStream = new HmacOutputStream();
}
 
Example #4
Source File: HMacTest.java    From nuls-v2 with MIT License 6 votes vote down vote up
@Test
public void test() {
    String iv = "00000000000000000000000000000000";
    String pubKeyA = "0410baeeb267e1d680adf4e2ad0eb61b6a3173657971c0209425406883f09ac639c7dad2baf8ab2d66e6b64c3cbd4dd488de91cc47b5ead45db299a929c4ebd468";
    String ciphertext = "b4d6ecbd61b3630abf609e102fcbd125";
    String dataToMac = iv + pubKeyA + ciphertext;
    String macKey = "785ac461b5c8607c39ec4f63e1004f19a77c371e6f91293f66d4c19c02524265";
    HMac mac = new HMac(new SHA256Digest());
    mac.init(new KeyParameter(HexUtil.decode(macKey)));

    byte[] byteArray = HexUtil.decode(dataToMac);
    mac.update(byteArray, 0, byteArray.length);
    byte[] macOutput = new byte[mac.getMacSize()];
    mac.doFinal(macOutput, 0);
    System.out.println(HexUtil.encode(macOutput));
    // hmac hex string: bcf0e6f47bf5622e3596104f4d1bcd0bc4f643a196f0520be834bb0b4d1043fa
}
 
Example #5
Source File: HmacSignUtil.java    From littleca with Apache License 2.0 6 votes vote down vote up
public static Mac getHmac(Digest digest, byte[] key) {
    KeyParameter keyParameter = new KeyParameter(key);
    HMac hmac = new HMac(new SM3Digest());
    hmac.init(keyParameter);

    return new Mac() {
        @Override
        public byte[] doFinal(byte[] bytes) {
            hmac.update(bytes, 0, bytes.length);
            byte[] result = new byte[hmac.getMacSize()];
            hmac.doFinal(result, 0);
            return result;
        }
    };

}
 
Example #6
Source File: NISTKDF.java    From InflatableDonkey with MIT License 6 votes vote down vote up
public static byte[]
        ctrHMac(byte[] keyDerivationKey, byte[] label, Supplier<Digest> digestSupplier, int keyLengthBytes) {

    logger.trace("<< ctrHMac() - keyDerivationKey: 0x{} label: {} digestSupplier: {} length: {}",
            Hex.toHexString(keyDerivationKey), Hex.toHexString(label), digestSupplier, keyLengthBytes);

    byte[] derivedKey = new byte[keyLengthBytes];

    // fixedInputData = label || 0x00 || dkLen in bits as 4 bytes big endian
    ByteBuffer buffer = ByteBuffer.allocate(label.length + 5);
    buffer.put(label);
    buffer.put((byte) 0);
    buffer.putInt(keyLengthBytes * 8);
    byte[] fixedInputData = buffer.array();
    logger.debug("-- ctrHMac() - fixed input data: 0x{}", Hex.toHexString(fixedInputData));

    HMac hMac = new HMac(digestSupplier.get());
    KDFCounterBytesGenerator generator = new KDFCounterBytesGenerator(hMac);
    generator.init(new KDFCounterParameters(keyDerivationKey, fixedInputData, R));
    generator.generateBytes(derivedKey, 0, derivedKey.length);

    logger.trace(">> ctrHMac() - derivedKey: 0x{}", Hex.toHexString(derivedKey));
    return derivedKey;
}
 
Example #7
Source File: HMACTest.java    From java_security with MIT License 5 votes vote down vote up
public static void bcHmacMD5()
{
	HMac hmac = new HMac(new MD5Digest());
	// 必须是16进制的字符,长度必须是2的倍数
	hmac.init(new KeyParameter(org.bouncycastle.util.encoders.Hex.decode("123456789abcde")));
	hmac.update(src.getBytes(), 0, src.getBytes().length);
	
	// 执行摘要
	byte[] hmacMD5Bytes = new byte[hmac.getMacSize()];
	hmac.doFinal(hmacMD5Bytes, 0);
	System.out.println("bc hmacMD5:" + org.bouncycastle.util.encoders.Hex.toHexString(hmacMD5Bytes));
	
}
 
Example #8
Source File: Hash.java    From web3j with Apache License 2.0 5 votes vote down vote up
public static byte[] hmacSha512(byte[] key, byte[] input) {
    HMac hMac = new HMac(new SHA512Digest());
    hMac.init(new KeyParameter(key));
    hMac.update(input, 0, input.length);
    byte[] out = new byte[64];
    hMac.doFinal(out, 0);
    return out;
}
 
Example #9
Source File: Smb3KeyDerivation.java    From jcifs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * @param sessionKey
 * @param label
 * @param context
 */
private static byte[] derive ( byte[] sessionKey, byte[] label, byte[] context ) {
    KDFCounterBytesGenerator gen = new KDFCounterBytesGenerator(new HMac(new SHA256Digest()));

    int r = 32;
    byte[] suffix = new byte[label.length + context.length + 5];
    // per bouncycastle
    // <li>1: K(i) := PRF( KI, [i]_2 || Label || 0x00 || Context || [L]_2 ) with the counter at the very beginning
    // of the fixedInputData (The default implementation has this format)</li>
    // with the parameters
    // <li>1. KDFCounterParameters(ki, null, "Label || 0x00 || Context || [L]_2]", 8);

    // all fixed inputs go into the suffix:
    // + label
    System.arraycopy(label, 0, suffix, 0, label.length);
    // + 1 byte 0x00
    // + context
    System.arraycopy(context, 0, suffix, label.length + 1, context.length);
    // + 4 byte (== r bits) big endian encoding of L
    suffix[ suffix.length - 1 ] = (byte) 128;

    DerivationParameters param = new KDFCounterParameters(sessionKey, null /* prefix */, suffix /* suffix */, r /* r */);
    gen.init(param);

    byte[] derived = new byte[16];
    gen.generateBytes(derived, 0, 16);
    return derived;
}
 
Example #10
Source File: CryptoPrimitives.java    From Clusion with GNU General Public License v3.0 5 votes vote down vote up
public static byte[] generateHmac(byte[] key, String msg) throws UnsupportedEncodingException {

		HMac hmac = new HMac(new SHA256Digest());
		byte[] result = new byte[hmac.getMacSize()];
		byte[] msgAry = msg.getBytes("UTF-8");
		hmac.init(new KeyParameter(key));
		hmac.reset();
		hmac.update(msgAry, 0, msgAry.length);
		hmac.doFinal(result, 0);
		return result;
	}
 
Example #11
Source File: CryptoPrimitives.java    From Clusion with GNU General Public License v3.0 5 votes vote down vote up
public static byte[] generateHmac(byte[] key, byte[] msg) throws UnsupportedEncodingException {

		HMac hmac = new HMac(new SHA256Digest());
		byte[] result = new byte[hmac.getMacSize()];
		hmac.init(new KeyParameter(key));
		hmac.reset();
		hmac.update(msg, 0, msg.length);
		hmac.doFinal(result, 0);
		return result;
	}
 
Example #12
Source File: CryptoPrimitives.java    From Clusion with GNU General Public License v3.0 5 votes vote down vote up
public static byte[] generateHmac512(byte[] key, String msg) throws UnsupportedEncodingException {

		HMac hmac = new HMac(new SHA512Digest());
		byte[] result = new byte[hmac.getMacSize()];
		byte[] msgAry = msg.getBytes("UTF-8");
		hmac.init(new KeyParameter(key));
		hmac.reset();
		hmac.update(msgAry, 0, msgAry.length);
		hmac.doFinal(result, 0);
		return result;
	}
 
Example #13
Source File: Smb3KeyDerivation.java    From jcifs-ng with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * @param sessionKey
 * @param label
 * @param context
 */
private static byte[] derive ( byte[] sessionKey, byte[] label, byte[] context ) {
    KDFCounterBytesGenerator gen = new KDFCounterBytesGenerator(new HMac(new SHA256Digest()));

    int r = 32;
    byte[] suffix = new byte[label.length + context.length + 5];
    // per bouncycastle
    // <li>1: K(i) := PRF( KI, [i]_2 || Label || 0x00 || Context || [L]_2 ) with the counter at the very beginning
    // of the fixedInputData (The default implementation has this format)</li>
    // with the parameters
    // <li>1. KDFCounterParameters(ki, null, "Label || 0x00 || Context || [L]_2]", 8);

    // all fixed inputs go into the suffix:
    // + label
    System.arraycopy(label, 0, suffix, 0, label.length);
    // + 1 byte 0x00
    // + context
    System.arraycopy(context, 0, suffix, label.length + 1, context.length);
    // + 4 byte (== r bits) big endian encoding of L
    suffix[ suffix.length - 1 ] = (byte) 128;

    DerivationParameters param = new KDFCounterParameters(sessionKey, null /* prefix */, suffix /* suffix */, r /* r */);
    gen.init(param);

    byte[] derived = new byte[16];
    gen.generateBytes(derived, 0, 16);
    return derived;
}
 
Example #14
Source File: Crypto.java    From webauthndemo with Apache License 2.0 5 votes vote down vote up
public static byte[] hmacSha256(byte[] key, byte[] data, int outputLength) {
  HMac hmac = new HMac(new SHA256Digest());
  hmac.init(new KeyParameter(key));
  hmac.update(data, 0, data.length);
  byte[] output = new byte[hmac.getMacSize()];
  hmac.doFinal(output, 0);
  return Arrays.copyOf(output, outputLength);
}
 
Example #15
Source File: CheckCodeScreen.java    From google-authenticator with Apache License 2.0 5 votes vote down vote up
static String getCheckCode(String secret)
    throws Base32String.DecodingException {
  final byte[] keyBytes = Base32String.decode(secret);
  Mac mac = new HMac(new SHA1Digest());
  mac.init(new KeyParameter(keyBytes));
  PasscodeGenerator pcg = new PasscodeGenerator(mac);
  return pcg.generateResponseCode(0L);
}
 
Example #16
Source File: TOTPMIDlet.java    From totp-me with Apache License 2.0 5 votes vote down vote up
/**
 * Generates the current token. If the token can't be generated it returns
 * an empty String.
 * 
 * @return current token or an empty String
 */
protected static String genToken(final long counter, final HMac hmac, final int digits) {
	if (hmac == null || digits <= 0) {
		return "";
	}

	// generate 8 byte HOTP counter value (RFC 4226)
	final byte msg[] = new byte[8];
	for (int i = 0; i < 8; i++) {
		msg[7 - i] = (byte) (counter >>> (i * 8));
	}

	// compute the HMAC
	final byte[] hash = new byte[hmac.getMacSize()];
	hmac.update(msg, 0, msg.length);
	hmac.doFinal(hash, 0);

	// Transform the HMAC to a HOTP value according to RFC 4226.
	final int off = hash[hash.length - 1] & 0xF;
	// Truncate the HMAC (look at RFC 4226 section 5.3, step 2).
	int binary = ((hash[off] & 0x7f) << 24) | ((hash[off + 1] & 0xff) << 16) | ((hash[off + 2] & 0xff) << 8)
			| ((hash[off + 3] & 0xff));

	// use requested number of digits
	final byte[] digitsArray = new byte[digits];
	for (int i = 0; i < digits; i++) {
		digitsArray[digits - 1 - i] = (byte) ('0' + (char) (binary % 10));
		binary /= 10;
	}
	return new String(digitsArray, 0, digits);
}
 
Example #17
Source File: TOTPMIDletTest.java    From totp-me with Apache License 2.0 5 votes vote down vote up
public void testTOTP() {
	HMac sha1Hmac = new HMac(new SHA1Digest());
	sha1Hmac.init(new KeyParameter(seed20));
	HMac sha256Hmac = new HMac(new SHA256Digest());
	sha256Hmac.init(new KeyParameter(seed32));
	HMac sha512Hmac = new HMac(new SHA512Digest());
	sha512Hmac.init(new KeyParameter(seed64));
	for (int i = 0; i < TEST_TIME.length; i++) {
		long counter = TOTPMIDlet.getCounter(TEST_TIME[i], TIMESTEP);
		assertEquals(SHA1_VALUES[i], TOTPMIDlet.genToken(counter, sha1Hmac, DIGITS));
		assertEquals(SHA256_VALUES[i], TOTPMIDlet.genToken(counter, sha256Hmac, DIGITS));
		assertEquals(SHA512_VALUES[i], TOTPMIDlet.genToken(counter, sha512Hmac, DIGITS));
	}
}
 
Example #18
Source File: Hash.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
public static byte[] hmacSha512(byte[] key, byte[] input) {
    HMac hMac = new HMac(new SHA512Digest());
    hMac.init(new KeyParameter(key));
    hMac.update(input, 0, input.length);
    byte[] out = new byte[64];
    hMac.doFinal(out, 0);
    return out;
}
 
Example #19
Source File: RLPxConnectionFactory.java    From incubator-tuweni with Apache License 2.0 5 votes vote down vote up
private static EthereumIESEncryptionEngine forDecryption(
    SecretKey privateKey,
    PublicKey ephemeralPublicKey,
    Bytes iv,
    Bytes commonMac) {
  CipherParameters pubParam = new ECPublicKeyParameters(ephemeralPublicKey.asEcPoint(), CURVE);
  CipherParameters privParam = new ECPrivateKeyParameters(privateKey.bytes().toUnsignedBigInteger(), CURVE);

  BasicAgreement agreement = new ECDHBasicAgreement();
  agreement.init(privParam);
  byte[] agreementValue =
      BigIntegers.asUnsignedByteArray(agreement.getFieldSize(), agreement.calculateAgreement(pubParam));

  IESWithCipherParameters iesWithCipherParameters = new IESWithCipherParameters(new byte[0], new byte[0], 128, 128);

  EthereumIESEncryptionEngine.ECIESHandshakeKDFFunction kdf =
      new EthereumIESEncryptionEngine.ECIESHandshakeKDFFunction(1, new SHA256Digest());
  kdf.init(new KDFParameters(agreementValue, iesWithCipherParameters.getDerivationV()));
  EthereumIESEncryptionEngine engine = new EthereumIESEncryptionEngine(
      agreement,
      kdf,
      new HMac(new SHA256Digest()),
      commonMac.toArrayUnsafe(),
      new BufferedBlockCipher(new SICBlockCipher(new AESEngine())));
  ParametersWithIV cipherParameters = new ParametersWithIV(iesWithCipherParameters, iv.toArrayUnsafe());
  engine.init(false, privParam, pubParam, cipherParameters);
  return engine;
}
 
Example #20
Source File: CryptoUtils.java    From hedera-sdk-java with Apache License 2.0 5 votes vote down vote up
static byte[] calcHmacSha384(KeyParameter cipherKey, byte[] input) {
    final HMac hmacSha384 = new HMac(new SHA384Digest());
    final byte[] output = new byte[hmacSha384.getMacSize()];

    hmacSha384.init(new KeyParameter(cipherKey.getKey(), 16, 16));
    hmacSha384.update(input, 0, input.length);
    hmacSha384.doFinal(output, 0);

    return output;
}
 
Example #21
Source File: Digest.java    From ontology-java-sdk with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static byte[] hmacSha512(byte[] keyBytes, byte[] text) {
	HMac hmac = new HMac(new SHA512Digest());
	byte[] resBuf = new byte[hmac.getMacSize()];
	CipherParameters pm = new KeyParameter(keyBytes);
	hmac.init(pm);
	hmac.update(text, 0, text.length);
	hmac.doFinal(resBuf, 0);
	return resBuf;
}
 
Example #22
Source File: SM3Util.java    From gmhelper with Apache License 2.0 5 votes vote down vote up
/**
 * 计算SM3 Mac值
 *
 * @param key     key值,可以是任意长度的字节数组
 * @param srcData 原文
 * @return Mac值,对于HMac-SM3来说是32字节
 */
public static byte[] hmac(byte[] key, byte[] srcData) {
    KeyParameter keyParameter = new KeyParameter(key);
    SM3Digest digest = new SM3Digest();
    HMac mac = new HMac(digest);
    mac.init(keyParameter);
    mac.update(srcData, 0, srcData.length);
    byte[] result = new byte[mac.getMacSize()];
    mac.doFinal(result, 0);
    return result;
}
 
Example #23
Source File: Sm3Util.java    From littleca with Apache License 2.0 5 votes vote down vote up
public static byte[] hmac(byte[] key, byte[] srcData) {
    KeyParameter keyParameter = new KeyParameter(key);
    SM3Digest digest = new SM3Digest();
    HMac mac = new HMac(digest);
    mac.init(keyParameter);
    mac.update(srcData, 0, srcData.length);
    byte[] result = new byte[mac.getMacSize()];
    mac.doFinal(result, 0);
    return result;
}
 
Example #24
Source File: RLPxConnectionFactory.java    From cava with Apache License 2.0 5 votes vote down vote up
private static EthereumIESEncryptionEngine forEncryption(
    PublicKey pubKey,
    Bytes iv,
    Bytes commonMac,
    KeyPair ephemeralKeyPair) {
  CipherParameters pubParam = new ECPublicKeyParameters(pubKey.asEcPoint(), CURVE);
  CipherParameters privParam =
      new ECPrivateKeyParameters(ephemeralKeyPair.secretKey().bytes().toUnsignedBigInteger(), CURVE);

  BasicAgreement agree = new ECDHBasicAgreement();
  agree.init(privParam);
  BigInteger z = agree.calculateAgreement(pubParam);
  byte[] zbytes = BigIntegers.asUnsignedByteArray(agree.getFieldSize(), z);

  IESWithCipherParameters iesWithCipherParameters = new IESWithCipherParameters(new byte[0], new byte[0], 128, 128);

  // Initialise the KDF.
  EthereumIESEncryptionEngine.ECIESHandshakeKDFFunction kdf =
      new EthereumIESEncryptionEngine.ECIESHandshakeKDFFunction(1, new SHA256Digest());
  kdf.init(new KDFParameters(zbytes, iesWithCipherParameters.getDerivationV()));
  EthereumIESEncryptionEngine engine = new EthereumIESEncryptionEngine(
      agree,
      kdf,
      new HMac(new SHA256Digest()),
      commonMac.toArrayUnsafe(),
      new BufferedBlockCipher(new SICBlockCipher(new AESEngine())));
  ParametersWithIV cipherParameters = new ParametersWithIV(iesWithCipherParameters, iv.toArrayUnsafe());
  engine.init(true, privParam, pubParam, cipherParameters);

  return engine;
}
 
Example #25
Source File: RLPxConnectionFactory.java    From cava with Apache License 2.0 5 votes vote down vote up
private static EthereumIESEncryptionEngine forDecryption(
    SecretKey privateKey,
    PublicKey ephemeralPublicKey,
    Bytes iv,
    Bytes commonMac) {
  CipherParameters pubParam = new ECPublicKeyParameters(ephemeralPublicKey.asEcPoint(), CURVE);
  CipherParameters privParam = new ECPrivateKeyParameters(privateKey.bytes().toUnsignedBigInteger(), CURVE);

  BasicAgreement agreement = new ECDHBasicAgreement();
  agreement.init(privParam);
  byte[] agreementValue =
      BigIntegers.asUnsignedByteArray(agreement.getFieldSize(), agreement.calculateAgreement(pubParam));

  IESWithCipherParameters iesWithCipherParameters = new IESWithCipherParameters(new byte[0], new byte[0], 128, 128);

  EthereumIESEncryptionEngine.ECIESHandshakeKDFFunction kdf =
      new EthereumIESEncryptionEngine.ECIESHandshakeKDFFunction(1, new SHA256Digest());
  kdf.init(new KDFParameters(agreementValue, iesWithCipherParameters.getDerivationV()));
  EthereumIESEncryptionEngine engine = new EthereumIESEncryptionEngine(
      agreement,
      kdf,
      new HMac(new SHA256Digest()),
      commonMac.toArrayUnsafe(),
      new BufferedBlockCipher(new SICBlockCipher(new AESEngine())));
  ParametersWithIV cipherParameters = new ParametersWithIV(iesWithCipherParameters, iv.toArrayUnsafe());
  engine.init(false, privParam, pubParam, cipherParameters);
  return engine;
}
 
Example #26
Source File: AESDecrypterBC.java    From fingen with Apache License 2.0 5 votes vote down vote up
public void init( String pwStr, int keySize, byte[] salt, byte[] pwVerification ) throws ZipException {
	byte[] pwBytes = pwStr.getBytes();
	
	super.saltBytes = salt;

	PBEParametersGenerator generator = new PKCS5S2ParametersGenerator();
	generator.init( pwBytes, salt, ITERATION_COUNT );

	cipherParameters = generator.generateDerivedParameters(KEY_SIZE_BIT*2 + 16);
	byte[] keyBytes = ((KeyParameter)cipherParameters).getKey();

	this.cryptoKeyBytes = new byte[ KEY_SIZE_BYTE ];
	System.arraycopy( keyBytes, 0, cryptoKeyBytes, 0, KEY_SIZE_BYTE );

	this.authenticationCodeBytes = new byte[ KEY_SIZE_BYTE ];
	System.arraycopy( keyBytes, KEY_SIZE_BYTE, authenticationCodeBytes, 0, KEY_SIZE_BYTE );

	// based on SALT + PASSWORD (password is probably correct)
	this.pwVerificationBytes = new byte[ 2 ];
	System.arraycopy( keyBytes, KEY_SIZE_BYTE*2, this.pwVerificationBytes, 0, 2 );

	if( !ByteArrayHelper.isEqual( this.pwVerificationBytes, pwVerification ) ) {
		throw new ZipException("wrong password - " + ByteArrayHelper.toString(this.pwVerificationBytes) + "/ " + ByteArrayHelper.toString(pwVerification));
	}

	// create the first 16 bytes of the key sequence again (using pw+salt)
	generator.init( pwBytes, salt, ITERATION_COUNT );
	cipherParameters = generator.generateDerivedParameters(KEY_SIZE_BIT);

	// checksum added to the end of the encrypted data, update on each encryption call
	this.mac = new HMac( new SHA1Digest() );
	mac.init( new KeyParameter(authenticationCodeBytes) );

	this.aesCipher = new SICBlockCipher(new AESEngine());
	this.blockSize = aesCipher.getBlockSize();

	// incremented on each 16 byte block and used as encryption NONCE (ivBytes)
	nonce = 1;
}
 
Example #27
Source File: BouncyCastleV1CryptoProvider.java    From paseto with MIT License 5 votes vote down vote up
@Override
public byte[] hmacSha384(byte[] m, byte[] key) {
	validateHmacSha384(m, key);

	Digest digest = new SHA384Digest();
	HMac hmac = new HMac(digest);

	hmac.init(new KeyParameter(key));
	byte[] out = new byte[hmac.getMacSize()];
	hmac.update(m, 0, m.length);
	hmac.doFinal(out, 0);
	return out;
}
 
Example #28
Source File: HMacWithSha256.java    From nuls-v2 with MIT License 5 votes vote down vote up
public static byte[] hmac(byte[] data, byte[] macKey) {
    HMac mac = new HMac(new SHA256Digest());
    mac.init(new KeyParameter(macKey));
    mac.update(data, 0, data.length);
    byte[] macOutput = new byte[mac.getMacSize()];
    mac.doFinal(macOutput, 0);
    return macOutput;
}
 
Example #29
Source File: SecP256K1BlockCipher.java    From nem.core with MIT License 4 votes vote down vote up
private static IESEngine createIesEngine() {
	return new IESEngine(
			new ECDHBasicAgreement(),
			new KDF2BytesGenerator(new SHA1Digest()),
			new HMac(new SHA1Digest()));
}
 
Example #30
Source File: AESEncrypterBC.java    From fingen with Apache License 2.0 4 votes vote down vote up
/**
 * Setup AES encryption based on pwBytes using WinZipAES approach
 * with SALT and pwVerification bytes based on password+salt.
 */
public void init( String pwStr, int keySize ) throws ZipException {
	byte[] pwBytes = pwStr.getBytes();
	PBEParametersGenerator generator = new PKCS5S2ParametersGenerator();
	this.saltBytes = createSalt();
	generator.init( pwBytes, saltBytes, ITERATION_COUNT );

	// create 2 byte[16] for two keys and one byte[2] for pwVerification
	// 1. encryption / 2. athentication (via HMAC/hash) /
	cipherParameters = generator.generateDerivedParameters(KEY_SIZE_BIT*2 + 16);
	byte[] keyBytes = ((KeyParameter)cipherParameters).getKey();

	this.cryptoKeyBytes = new byte[ KEY_SIZE_BYTE ];
	System.arraycopy( keyBytes, 0, cryptoKeyBytes, 0, KEY_SIZE_BYTE );

	this.authenticationCodeBytes = new byte[ KEY_SIZE_BYTE ];
	System.arraycopy( keyBytes, KEY_SIZE_BYTE, authenticationCodeBytes, 0, KEY_SIZE_BYTE );

	// based on SALT + PASSWORD (password is probably correct)
	this.pwVerificationBytes = new byte[ 2 ];
	System.arraycopy( keyBytes, KEY_SIZE_BYTE*2, pwVerificationBytes, 0, 2 );

	// create the first 16 bytes of the key sequence again (using pw+salt)
	generator.init( pwBytes, saltBytes, ITERATION_COUNT );
	cipherParameters = generator.generateDerivedParameters(KEY_SIZE_BIT);

	// checksum added to the end of the encrypted data, update on each encryption call
	this.mac = new HMac( new SHA1Digest() );
	mac.init( new KeyParameter(authenticationCodeBytes) );

	this.aesCipher = new SICBlockCipher(new AESEngine());
	this.blockSize = aesCipher.getBlockSize();

	// incremented on each 16 byte block and used as encryption NONCE (ivBytes)
	nonce = 1;
	
	if( LOG.isLoggable(Level.FINEST) ) {
		LOG.finest( "pwBytes   = " + ByteArrayHelper.toString(pwBytes) + " - " + pwBytes.length );
		LOG.finest( "salt      = " + ByteArrayHelper.toString(saltBytes) + " - " + saltBytes.length );
		LOG.finest( "pwVerif   = " + ByteArrayHelper.toString(pwVerificationBytes) + " - " + pwVerificationBytes.length );
	}
}