org.bouncycastle.crypto.params.KeyParameter Java Examples

The following examples show how to use org.bouncycastle.crypto.params.KeyParameter. 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: SecurityHandler.java    From sambox with Apache License 2.0 7 votes vote down vote up
/**
 * Encrypt or decrypt data with AES256.
 *
 * @param data The data to encrypt.
 * @param output The output to write the encrypted data to.
 *
 * @throws IOException If there is an error reading the data.
 */
private void decryptDataAES256(InputStream data, OutputStream output) throws IOException
{
    byte[] iv = new byte[16];

    // read IV from stream
    int ivSize = data.read(iv);
    if (ivSize == -1)
    {
        return;
    }

    if (ivSize != iv.length)
    {
        throw new IOException("AES initialization vector not fully read: only " + ivSize
                + " bytes read instead of " + iv.length);
    }
    PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(
            new CBCBlockCipher(new AESFastEngine()));
    cipher.init(false, new ParametersWithIV(new KeyParameter(encryptionKey), iv));
    try (CipherInputStream cis = new CipherInputStream(data, cipher))
    {
        IOUtils.copy(cis, output);
    }
}
 
Example #2
Source File: AESEncrypt.java    From nuls-v2 with MIT License 6 votes vote down vote up
/**
 * 数据通过KeyParameter解密
 *
 * @param dataToDecrypt 需要解密的数据
 * @param aesKey        秘钥
 * @return 解密后的数据
 */
public static byte[] decrypt(EncryptedData dataToDecrypt, KeyParameter aesKey) throws CryptoException {
    HexUtil.checkNotNull(dataToDecrypt);
    HexUtil.checkNotNull(aesKey);

    try {
        ParametersWithIV keyWithIv = new ParametersWithIV(new KeyParameter(aesKey.getKey()), dataToDecrypt.getInitialisationVector());

        // Decrypt the validator.
        BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));
        cipher.init(false, keyWithIv);

        byte[] cipherBytes = dataToDecrypt.getEncryptedBytes();
        byte[] decryptedBytes = new byte[cipher.getOutputSize(cipherBytes.length)];
        final int length1 = cipher.processBytes(cipherBytes, 0, cipherBytes.length, decryptedBytes, 0);
        final int length2 = cipher.doFinal(decryptedBytes, length1);

        return Arrays.copyOf(decryptedBytes, length1 + length2);
    } catch (Exception e) {
        throw new CryptoException();
    }
}
 
Example #3
Source File: EmulatorP11Identity.java    From xipki with Apache License 2.0 6 votes vote down vote up
private byte[] aesGmac(P11Params params, byte[] contentToSign) throws P11TokenException {
  if (params == null) {
    throw new P11TokenException("iv may not be null");
  }

  byte[] iv;
  if (params instanceof P11Params.P11IVParams) {
    iv = ((P11Params.P11IVParams) params).getIV();
  } else {
    throw new P11TokenException("params must be instanceof P11IVParams");
  }

  GMac gmac = new GMac(new GCMBlockCipher(new AESEngine()));
  ParametersWithIV paramsWithIv =
      new ParametersWithIV(new KeyParameter(signingKey.getEncoded()), iv);
  gmac.init(paramsWithIv);
  gmac.update(contentToSign, 0, contentToSign.length);
  byte[] signature = new byte[gmac.getMacSize()];
  gmac.doFinal(signature, 0);
  return signature;
}
 
Example #4
Source File: Metodos.java    From ExamplesAndroid with Apache License 2.0 6 votes vote down vote up
public String testEncryptRijndael(String value,String key) throws DataLengthException, IllegalStateException, InvalidCipherTextException {
    BlockCipher engine = new RijndaelEngine(256);
    BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(engine), new ZeroBytePadding());

    byte[] keyBytes = key.getBytes();
    cipher.init(true, new KeyParameter(keyBytes));

    byte[] input = value.getBytes();
    byte[] cipherText = new byte[cipher.getOutputSize(input.length)];

    int cipherLength = cipher.processBytes(input, 0, input.length, cipherText, 0);
    cipher.doFinal(cipherText, cipherLength);

    String result = new String(Base64.encode(cipherText));
    //Log.e("testEncryptRijndael : " , result);
    return  result;
}
 
Example #5
Source File: Mnemonic.java    From hedera-sdk-java with Apache License 2.0 6 votes vote down vote up
@Internal
public byte[] toSeed(String passphrase) {
    final String salt = "mnemonic" + passphrase;

    // BIP-39 seed generation
    final PKCS5S2ParametersGenerator pbkdf2 = new PKCS5S2ParametersGenerator(new SHA512Digest());
    pbkdf2.init(
        toString().getBytes(StandardCharsets.UTF_8),
        salt.getBytes(StandardCharsets.UTF_8),
        2048);

    final KeyParameter key = (KeyParameter) pbkdf2.generateDerivedParameters(512);
    return key.getKey();
}
 
Example #6
Source File: RLPxConnection.java    From cava with Apache License 2.0 6 votes vote down vote up
RLPxConnection(
    Bytes32 aesSecret,
    Bytes32 macSecret,
    Bytes32 token,
    Bytes egressMac,
    Bytes ingressMac,
    SECP256K1.PublicKey publicKey,
    SECP256K1.PublicKey peerPublicKey) {
  this.aesSecret = aesSecret;
  this.macSecret = macSecret;
  this.token = token;

  KeyParameter macKey = new KeyParameter(macSecret.toArrayUnsafe());
  macEncryptionEngine = new AESEngine();
  macEncryptionEngine.init(true, macKey);

  updateEgress(egressMac);
  updateIngress(ingressMac);
  this.publicKey = publicKey;
  this.peerPublicKey = peerPublicKey;
}
 
Example #7
Source File: BCStrongAESEncryption.java    From Hive2Hive with MIT License 6 votes vote down vote up
private static byte[] processAESCipher(boolean encrypt, byte[] data, SecretKey key, byte[] initVector)
		throws DataLengthException, IllegalStateException, InvalidCipherTextException {
	// seat up engine, block cipher mode and padding
	AESEngine aesEngine = new AESEngine();
	CBCBlockCipher cbc = new CBCBlockCipher(aesEngine);
	PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(cbc);

	// apply parameters
	CipherParameters parameters = new ParametersWithIV(new KeyParameter(key.getEncoded()), initVector);
	cipher.init(encrypt, parameters);

	// process ciphering
	byte[] output = new byte[cipher.getOutputSize(data.length)];

	int bytesProcessed1 = cipher.processBytes(data, 0, data.length, output, 0);
	int bytesProcessed2 = cipher.doFinal(output, bytesProcessed1);
	byte[] result = new byte[bytesProcessed1 + bytesProcessed2];
	System.arraycopy(output, 0, result, 0, result.length);
	return result;
}
 
Example #8
Source File: XTSAESBlockCipherTest.java    From InflatableDonkey with MIT License 6 votes vote down vote up
public XTSAESBlockCipherTest() throws IOException {
    // Key = key1 | key2
    byte[] keyData = Arrays.concatenate(VECTOR_4.key1(), VECTOR_4.key2());
    key = new KeyParameter(keyData);
    dataUnitLength = VECTOR_4.ctx().length;

    // Vectors 4, 5, 6 are sequential 512 byte data units starting from data unit sequence number 0.
    ByteArrayOutputStream ptxs = new ByteArrayOutputStream();
    ptxs.write(VECTOR_4.ptx());
    ptxs.write(VECTOR_5.ptx());
    ptxs.write(VECTOR_6.ptx());
    ptx = ptxs.toByteArray();

    ByteArrayOutputStream ctxs = new ByteArrayOutputStream();
    ctxs.write(VECTOR_4.ctx());
    ctxs.write(VECTOR_5.ctx());
    ctxs.write(VECTOR_6.ctx());
    ctx = ctxs.toByteArray();
}
 
Example #9
Source File: XTSTweakTest.java    From InflatableDonkey with MIT License 6 votes vote down vote up
@Test
@Parameters
public void test(XTSAESTestVector testVector) {
    KeyParameter key = new KeyParameter(testVector.key2());
    XTSTweak tweak = new XTSTweak()
            .init(key)
            .reset(testVector.dataUnitSequenceNumber());

    byte[] twk = testVector.twk();
    for (int i = 0; i < twk.length; i += BLOCK_LENGTH) {
        byte[] value = tweak.value();
        byte[] expected = Arrays.copyOfRange(twk, i, i + BLOCK_LENGTH);

        assertArrayEquals(testVector.id(), expected, value);
        tweak.next();
    }
}
 
Example #10
Source File: AESEncrypt.java    From nuls-v2 with MIT License 6 votes vote down vote up
/**
 * 数据通过KeyParameter和初始化向量加密
 *
 * @param plainBytes 需要加密的数据
 * @param iv         初始化向量
 * @param aesKey     秘钥
 * @return 加密后的数据
 */
public static EncryptedData encrypt(byte[] plainBytes, byte[] iv, KeyParameter aesKey) throws RuntimeException {
    HexUtil.checkNotNull(plainBytes);
    HexUtil.checkNotNull(aesKey);
    try {
        if (iv == null) {
            iv = EncryptedData.DEFAULT_IV;
            //SECURE_RANDOM.nextBytes(iv);
        }
        ParametersWithIV keyWithIv = new ParametersWithIV(aesKey, iv);
        // Encrypt using AES.
        BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));
        cipher.init(true, keyWithIv);
        byte[] encryptedBytes = new byte[cipher.getOutputSize(plainBytes.length)];
        final int length1 = cipher.processBytes(plainBytes, 0, plainBytes.length, encryptedBytes, 0);
        final int length2 = cipher.doFinal(encryptedBytes, length1);

        return new EncryptedData(iv, Arrays.copyOf(encryptedBytes, length1 + length2));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #11
Source File: CredStashBouncyCastleCrypto.java    From jcredstash with Apache License 2.0 6 votes vote down vote up
private byte[] encryptOrDecrypt(byte[] key, byte[] contents, boolean forEncryption) {

        // Credstash uses standard AES
        BlockCipher engine = new AESFastEngine();

        // Credstash uses CTR mode
        StreamBlockCipher cipher = new SICBlockCipher(engine);

        cipher.init(forEncryption, new ParametersWithIV(new KeyParameter(key), INITIALIZATION_VECTOR));

        byte[] resultBytes = new byte[contents.length];
        int contentsOffset = 0;
        int resultOffset = 0;
        cipher.processBytes(contents, contentsOffset, contents.length, resultBytes, resultOffset);
        return resultBytes;
    }
 
Example #12
Source File: Downloader.java    From Zom-Android-XMPP with GNU General Public License v3.0 6 votes vote down vote up
public static InputStream setupInputStream(InputStream is, byte[] keyAndIv) {
    if (keyAndIv != null && keyAndIv.length == 48) {
        byte[] key = new byte[32];
        byte[] iv = new byte[16];
        System.arraycopy(keyAndIv, 0, iv, 0, 16);
        System.arraycopy(keyAndIv, 16, key, 0, 32);
        AEADBlockCipher cipher = new GCMBlockCipher(new AESEngine());
        cipher.init(true, new AEADParameters(new KeyParameter(key), 128, iv));
        return new CipherInputStream(is, cipher);
    } else {
        return is;
    }
}
 
Example #13
Source File: BouncycastleTests.java    From super-cloudops with Apache License 2.0 6 votes vote down vote up
public static void des8Test() {
	byte[] key = new CodecSource("12345678").getBytes();
	byte[] input = new CodecSource("12345678").getBytes();
	byte[] out = new byte[8];

	// 使用DESEngine进行加密
	DESEngine desEngine = new DESEngine();
	desEngine.init(true, new KeyParameter(key));
	desEngine.processBlock(input, 0, out, 0);
	System.out.println("des encrypt=" + new CodecSource(out).toBase64());

	// 使用DESEngine进行解密
	desEngine.init(false, new KeyParameter(key));
	desEngine.processBlock(input, 0, out, 0);
	System.out.println("des decrypt=" + new CodecSource(out).toBase64());
}
 
Example #14
Source File: AESGCM.java    From InflatableDonkey with MIT License 5 votes vote down vote up
/**
 * Returns decrypted data.
 *
 * @param key
 * @param nonce nonce/ IV
 * @param header
 * @param encryptedData
 * @param tag
 * @param optional optional AADBytes (post header)
 * @return decrypted data
 * @throws IllegalArgumentException on decryption exceptions
 * @throws NullPointerException on null arguments
 */
public static byte[] decrypt(
        byte[] key,
        byte[] nonce,
        byte[] header,
        byte[] encryptedData,
        byte[] tag,
        Optional<byte[]> optional) {

    try {
        GCMBlockCipher cipher = new GCMBlockCipher(new AESFastEngine());
        AEADParameters parameters = new AEADParameters(new KeyParameter(key), tag.length * 8, nonce, header);
        cipher.init(false, parameters);

        if (optional.isPresent()) {
            byte[] aadBytes = optional.get();
            cipher.processAADBytes(aadBytes, 0, aadBytes.length);
        }

        byte[] out = new byte[cipher.getOutputSize(encryptedData.length + tag.length)];

        int pos = cipher.processBytes(encryptedData, 0, encryptedData.length, out, 0);
        pos += cipher.processBytes(tag, 0, tag.length, out, pos);
        pos += cipher.doFinal(out, pos);

        return Arrays.copyOf(out, pos);

    } catch (IllegalStateException | InvalidCipherTextException | RuntimeCryptoException ex) {
        throw new IllegalStateException("GCM decrypt error", ex);
    }
}
 
Example #15
Source File: FileBlockCipherTest.java    From InflatableDonkey with MIT License 5 votes vote down vote up
@Test
public void testEncryption() {
    KeyParameter key = new KeyParameter(KEY);
    byte[] plaintext = Base64.getDecoder().decode(PLAINTEXT);
    byte[] ciphertext = Base64.getDecoder().decode(CIPHERTEXT);

    DPAESCBCCipher cipher = new DPAESCBCCipher();
    cipher.init(true, key);

    byte[] out = process(cipher, plaintext);
    assertArrayEquals(out, ciphertext);
}
 
Example #16
Source File: ChachaEncoder.java    From HAP-Java with MIT License 5 votes vote down vote up
public byte[] encodeCiphertext(byte[] plaintext, byte[] additionalData) throws IOException {
  KeyParameter macKey = initRecordMAC(encryptCipher);

  byte[] ciphertext = new byte[plaintext.length];
  encryptCipher.processBytes(plaintext, 0, plaintext.length, ciphertext, 0);

  byte[] calculatedMAC = PolyKeyCreator.create(macKey, additionalData, ciphertext);

  byte[] ret = new byte[ciphertext.length + 16];
  System.arraycopy(ciphertext, 0, ret, 0, ciphertext.length);
  System.arraycopy(calculatedMAC, 0, ret, ciphertext.length, 16);
  return ret;
}
 
Example #17
Source File: AesCipher.java    From AgentX with Apache License 2.0 5 votes vote down vote up
@Override
protected void _init(boolean isEncrypt, byte[] iv) {
    String keyStr = new String(key.getEncoded());
    ParametersWithIV params = new ParametersWithIV(
            new KeyParameter(KeyHelper.generateKeyDigest(keyLength, keyStr)), iv
    );
    cipher.init(isEncrypt, params);
}
 
Example #18
Source File: Wallet.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
private static byte[] generateAes128CtrDerivedKey(
        byte[] password, byte[] salt, int c, String prf) throws CipherException {

    if (!prf.equals("hmac-sha256")) {
        throw new CipherException("Unsupported prf:" + prf);
    }

    // Java 8 supports this, but you have to convert the password to a character array, see
    // http://stackoverflow.com/a/27928435/3211687

    PKCS5S2ParametersGenerator gen = new PKCS5S2ParametersGenerator(new SHA256Digest());
    gen.init(password, salt, c);
    return ((KeyParameter) gen.generateDerivedParameters(256)).getKey();
}
 
Example #19
Source File: XTSCore.java    From InflatableDonkey with MIT License 5 votes vote down vote up
XTSCore init(boolean forEncryption, KeyParameter key) throws IllegalArgumentException {
    byte[] k = ((KeyParameter) key).getKey();
    if (k.length != 32 && k.length != 64) {
        throw new IllegalArgumentException("bad key length: " + k.length);
    }
    byte[] key1 = Arrays.copyOfRange(k, 0, k.length / 2);
    byte[] key2 = Arrays.copyOfRange(k, k.length / 2, k.length);

    return init(forEncryption, new KeyParameter(key1), new KeyParameter(key2));
}
 
Example #20
Source File: MnemonicUtils.java    From web3j with Apache License 2.0 5 votes vote down vote up
/**
 * To create a binary seed from the mnemonic, we use the PBKDF2 function with a mnemonic
 * sentence (in UTF-8 NFKD) used as the password and the string "mnemonic" + passphrase (again
 * in UTF-8 NFKD) used as the salt. The iteration count is set to 2048 and HMAC-SHA512 is used
 * as the pseudo-random function. The length of the derived key is 512 bits (= 64 bytes).
 *
 * @param mnemonic The input mnemonic which should be 128-160 bits in length containing only
 *     valid words
 * @param passphrase The passphrase which will be used as part of salt for PBKDF2 function
 * @return Byte array representation of the generated seed
 */
public static byte[] generateSeed(String mnemonic, String passphrase) {
    if (isMnemonicEmpty(mnemonic)) {
        throw new IllegalArgumentException("Mnemonic is required to generate a seed");
    }
    passphrase = passphrase == null ? "" : passphrase;

    String salt = String.format("mnemonic%s", passphrase);
    PKCS5S2ParametersGenerator gen = new PKCS5S2ParametersGenerator(new SHA512Digest());
    gen.init(mnemonic.getBytes(UTF_8), salt.getBytes(UTF_8), SEED_ITERATIONS);

    return ((KeyParameter) gen.generateDerivedParameters(SEED_KEY_SIZE)).getKey();
}
 
Example #21
Source File: CryptoUtils.java    From warp10-platform with Apache License 2.0 5 votes vote down vote up
/**
 * Unwrap byte [ ].
 *
 * @param key  the key
 * @param data the data
 * @return the byte [ ]
 */
public static byte[] unwrap(byte[] key, byte[] data) {
  //
  // Decrypt the encrypted data
  //

  AESWrapEngine engine = new AESWrapEngine();
  CipherParameters params = new KeyParameter(key);
  engine.init(false, params);

  try {
    byte[] decrypted = engine.unwrap(data, 0, data.length);
    //
    // Unpad the decrypted data
    //

    PKCS7Padding padding = new PKCS7Padding();
    int padcount = padding.padCount(decrypted);

    //
    // Remove padding
    //

    decrypted = Arrays.copyOfRange(decrypted, 0, decrypted.length - padcount);

    return decrypted;
  } catch (InvalidCipherTextException icte) {
    return null;
  }
}
 
Example #22
Source File: AES256CBCTest.java    From nuls-v2 with MIT License 5 votes vote down vote up
@Test
public void test() {
    // 0da59e256e2ab8e510bfd90e020264e396e6d4e028d2c6f565810c58e7c9eb7d785ac461b5c8607c39ec4f63e1004f19a77c371e6f91293f66d4c19c02524265
    EncryptedData encrypt = AESEncrypt.encrypt("test".getBytes(), new byte[16],
            new KeyParameter(HexUtil.decode("0da59e256e2ab8e510bfd90e020264e396e6d4e028d2c6f565810c58e7c9eb7d")));
    System.out.println(HexUtil.encode(encrypt.getInitialisationVector()));
    System.out.println(HexUtil.encode(encrypt.getEncryptedBytes()));
    // aes256-cbc hex string: b4d6ecbd61b3630abf609e102fcbd125
}
 
Example #23
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 #24
Source File: BCPoly1305MacHelper.java    From archistar-smc with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Computes the MAC of the specified length for the given share with the given key.
 *
 * @param data the data to create the MAC for
 * @param key the key to use for computing the MAC
 * @return the message authentication code (tag or MAC) for this share
 * @throws InvalidKeyException thrown if an InvalidKeyException occurred
 */
@Override
public byte[] computeMAC(byte[] data, byte[] key) throws InvalidKeyException {

    byte[] result = new byte[mac.getMacSize()];

    Poly1305KeyGenerator.clamp(key);

    mac.init(new KeyParameter(key));
    mac.update(data, 0, data.length);
    mac.doFinal(result, 0);
    return result;
}
 
Example #25
Source File: AESBouncycastleUtils.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
/**
 * Method for AES ECB operation, internal call
 * 
 * @param key
 * @param src
 * @param encrypting
 * @return
 * @throws GeneralSecurityException
 */
private static byte[] doAESECB(byte[] key, byte[] src, boolean encrypting) throws GeneralSecurityException {
	byte[] result = new byte[src.length];
	try {
		BufferedBlockCipher engine = new BufferedBlockCipher(new AESEngine());
		engine.init(encrypting, new KeyParameter(key));
		int len = engine.processBytes(src, 0, src.length, result, 0);
		engine.doFinal(result, len);
	} catch (InvalidCipherTextException e) {
		throw new GeneralSecurityException(e);
	}
	return result;
}
 
Example #26
Source File: BouncyCastleV1CryptoProvider.java    From paseto with MIT License 5 votes vote down vote up
private BufferedBlockCipher ase256CtrCipher(boolean forEncryption, byte[] key, byte[] iv) {
	BlockCipher engine = new AESEngine();
	BufferedBlockCipher cipher = new BufferedBlockCipher(new SICBlockCipher(engine));
	CipherParameters params = new ParametersWithIV(new KeyParameter(key), iv);

	cipher.init(forEncryption, params);
	return cipher;
}
 
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: PseudoRandomFunctionAES.java    From protect with MIT License 5 votes vote down vote up
public PseudoRandomFunctionAES(final PrfKey key)  {
	super(key);

	// Create CMAC instance based on AES
	final BlockCipher cipher = new AESEngine();
    this.cipherMac = new CMac(cipher);
    
    // Initialize with key
    final KeyParameter params = new KeyParameter(key.getKeyBytes());
    cipherMac.init(params);
}
 
Example #29
Source File: BCMacHelper.java    From archistar-smc with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Computes the MAC of the specified length for the given share with the given key.
 *
 * @param data the data to create the MAC for
 * @param key the key to use for computing the MAC
 * @return the message authentication code (tag or MAC) for this share
 * @throws InvalidKeyException thrown if an InvalidKeyException occurred
 */
@Override
public byte[] computeMAC(byte[] data, byte[] key) throws InvalidKeyException {

    byte[] result = new byte[keySize];

    mac.init(new KeyParameter(key));
    mac.update(data, 0, data.length);
    mac.doFinal(result, 0);
    return result;
}
 
Example #30
Source File: PBKDF2CipherProvider.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
protected Cipher getInitializedCipher(EncryptionMethod encryptionMethod, String password, byte[] salt, byte[] iv, int keyLength, boolean encryptMode) throws Exception {
    if (encryptionMethod == null) {
        throw new IllegalArgumentException("The encryption method must be specified");
    }

    if (!encryptionMethod.isCompatibleWithStrongKDFs()) {
        throw new IllegalArgumentException(encryptionMethod.name() + " is not compatible with PBKDF2");
    }

    String algorithm = encryptionMethod.getAlgorithm();

    final String cipherName = CipherUtility.parseCipherFromAlgorithm(algorithm);
    if (!CipherUtility.isValidKeyLength(keyLength, cipherName)) {
        throw new IllegalArgumentException(String.valueOf(keyLength) + " is not a valid key length for " + cipherName);
    }

    if (StringUtils.isEmpty(password)) {
        throw new IllegalArgumentException("Encryption with an empty password is not supported");
    }

    if (salt == null || salt.length < DEFAULT_SALT_LENGTH) {
        throw new IllegalArgumentException("The salt must be at least " + DEFAULT_SALT_LENGTH + " bytes. To generate a salt, use PBKDF2CipherProvider#generateSalt()");
    }

    PKCS5S2ParametersGenerator gen = new PKCS5S2ParametersGenerator(this.prf);
    gen.init(password.getBytes(StandardCharsets.UTF_8), salt, getIterationCount());
    byte[] dk = ((KeyParameter) gen.generateDerivedParameters(keyLength)).getKey();
    SecretKey tempKey = new SecretKeySpec(dk, algorithm);

    KeyedCipherProvider keyedCipherProvider = new AESKeyedCipherProvider();
    return keyedCipherProvider.getCipher(encryptionMethod, tempKey, iv, encryptMode);
}