org.bouncycastle.crypto.modes.SICBlockCipher Java Examples

The following examples show how to use org.bouncycastle.crypto.modes.SICBlockCipher. 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: Framer.java    From besu with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new framer out of the handshake secrets derived during the cryptographic handshake.
 *
 * @param secrets The handshake secrets.
 */
public Framer(final HandshakeSecrets secrets) {
  this.secrets = secrets;

  final KeyParameter aesKey = new KeyParameter(secrets.getAesSecret());
  final KeyParameter macKey = new KeyParameter(secrets.getMacSecret());

  encryptor = new SICBlockCipher(new AESEngine());
  encryptor.init(true, new ParametersWithIV(aesKey, IV));

  decryptor = new SICBlockCipher(new AESEngine());
  decryptor.init(false, new ParametersWithIV(aesKey, IV));

  macEncryptor = new AESEngine();
  macEncryptor.init(true, macKey);
}
 
Example #2
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 #3
Source File: RLPxConnection.java    From incubator-tuweni with Apache License 2.0 5 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;

  KeyParameter aesKey = new KeyParameter(aesSecret.toArrayUnsafe());

  byte[] IV = new byte[16];
  Arrays.fill(IV, (byte) 0);

  decryptionCipher = new SICBlockCipher(new AESEngine());
  decryptionCipher.init(false, new ParametersWithIV(aesKey, IV));

  encryptionCipher = new SICBlockCipher(new AESEngine());
  encryptionCipher.init(true, new ParametersWithIV(aesKey, IV));
}
 
Example #4
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 #5
Source File: ECKey.java    From javasdk with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Decrypt cipher by AES in SIC(also know as CTR) mode
 *
 * @param cipher -proper cipher
 * @return decrypted cipher, equal length to the cipher.
 * @deprecated should not use EC private scalar value as an AES key
 */
public byte[] decryptAES(byte[] cipher) {

    if (privKey == null) {
        throw new MissingPrivateKeyException();
    }
    if (!(privKey instanceof BCECPrivateKey)) {
        throw new UnsupportedOperationException("Cannot use the private key as an AES key");
    }


    AESFastEngine engine = new AESFastEngine();
    SICBlockCipher ctrEngine = new SICBlockCipher(engine);

    KeyParameter key = new KeyParameter(BigIntegers.asUnsignedByteArray(((BCECPrivateKey) privKey).getD()));
    ParametersWithIV params = new ParametersWithIV(key, new byte[16]);

    ctrEngine.init(false, params);

    int i = 0;
    byte[] out = new byte[cipher.length];
    while (i < cipher.length) {
        ctrEngine.processBlock(cipher, i, out, i);
        i += engine.getBlockSize();
        if (cipher.length - i < engine.getBlockSize())
            break;
    }

    // process left bytes
    if (cipher.length - i > 0) {
        byte[] tmpBlock = new byte[16];
        System.arraycopy(cipher, i, tmpBlock, 0, cipher.length - i);
        ctrEngine.processBlock(tmpBlock, 0, tmpBlock, 0);
        System.arraycopy(tmpBlock, 0, out, i, cipher.length - i);
    }

    return out;
}
 
Example #6
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 #7
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 #8
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 #9
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 #10
Source File: RLPxConnectionFactory.java    From incubator-tuweni with Apache License 2.0 4 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 #11
Source File: RLPxConnection.java    From cava with Apache License 2.0 4 votes vote down vote up
public RLPxMessage readFrame(Bytes messageFrame) {
  if (messageFrame.size() < 32) {
    return null;
  }

  KeyParameter aesKey = new KeyParameter(aesSecret.toArrayUnsafe());

  byte[] IV = new byte[16];
  Arrays.fill(IV, (byte) 0);

  SICBlockCipher decryptionCipher = new SICBlockCipher(new AESEngine());
  decryptionCipher.init(false, new ParametersWithIV(aesKey, IV));

  Bytes macBytes = messageFrame.slice(16, 16);
  Bytes headerBytes = messageFrame.slice(0, 16);

  Bytes decryptedHeader = Bytes.wrap(new byte[16]);
  decryptionCipher.processBytes(headerBytes.toArrayUnsafe(), 0, 16, decryptedHeader.toArrayUnsafe(), 0);
  int frameSize = decryptedHeader.get(0) & 0xff;
  frameSize = (frameSize << 8) + (decryptedHeader.get(1) & 0xff);
  frameSize = (frameSize << 8) + (decryptedHeader.get(2) & 0xff);
  int pad = frameSize % 16 == 0 ? 0 : 16 - frameSize % 16;

  if (messageFrame.size() < 32 + frameSize + pad + 16) {
    return null;
  }

  Bytes expectedMac = calculateMac(headerBytes, true);

  if (!macBytes.equals(expectedMac)) {
    throw new InvalidMACException(
        String.format(
            "Header MAC did not match expected MAC; expected: %s, received: %s",
            expectedMac.toHexString(),
            macBytes.toHexString()));
  }

  Bytes frameData = messageFrame.slice(32, frameSize);
  Bytes frameMac = messageFrame.slice(32 + frameSize + pad, 16);

  Bytes newFrameMac = Bytes.wrap(new byte[16]);
  Bytes frameMacSeed = updateIngress(messageFrame.slice(32, frameSize + pad));
  macEncryptionEngine.processBlock(frameMacSeed.toArrayUnsafe(), 0, newFrameMac.toArrayUnsafe(), 0);
  Bytes expectedFrameMac = updateIngress(newFrameMac.xor(frameMacSeed.slice(0, 16))).slice(0, 16);
  if (!expectedFrameMac.equals(frameMac)) {
    throw new InvalidMACException(
        String.format(
            "Frame MAC did not match expected MAC; expected: %s, received: %s",
            expectedFrameMac.toHexString(),
            frameMac.toHexString()));
  }

  Bytes decryptedFrameData = Bytes.wrap(new byte[frameData.size()]);
  decryptionCipher
      .processBytes(frameData.toArrayUnsafe(), 0, frameData.size(), decryptedFrameData.toArrayUnsafe(), 0);

  int messageType = RLP.decodeInt(decryptedFrameData.slice(0, 1));

  Bytes messageData = decryptedFrameData.slice(1);
  if (applySnappyCompression) {
    try {
      messageData = Bytes.wrap(Snappy.uncompress(messageData.toArrayUnsafe()));
    } catch (IOException e) {
      throw new IllegalArgumentException(e);
    }
  }

  return new RLPxMessage(messageType, messageData, 32 + frameSize + pad + 16);
}
 
Example #12
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 );
	}
}