org.bouncycastle.crypto.InvalidCipherTextException Java Examples

The following examples show how to use org.bouncycastle.crypto.InvalidCipherTextException. 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: GCMDataB.java    From InflatableDonkey with MIT License 7 votes vote down vote up
public static byte[] decrypt(byte[] key, byte[] data) {
    // TODO utilize GCMAES#decrypt method
    try {
        if (data.length < NONCE_LENGTH + TAG_LENGTH) {
            throw new IllegalArgumentException("data packet too short");
        }

        int cipherTextLength = data.length - NONCE_LENGTH - TAG_LENGTH;

        byte[] nonce = Arrays.copyOf(data, NONCE_LENGTH);

        GCMBlockCipher cipher = new GCMBlockCipher(new AESFastEngine());
        AEADParameters parameters = new AEADParameters(new KeyParameter(key), TAG_LENGTH * 8, nonce);
        cipher.init(false, parameters);

        byte[] out = new byte[cipher.getOutputSize(cipherTextLength + TAG_LENGTH)];

        int pos = cipher.processBytes(data, NONCE_LENGTH, data.length - NONCE_LENGTH, out, 0);
        pos += cipher.doFinal(out, pos);

        return Arrays.copyOf(out, pos);

    } catch (IllegalStateException | InvalidCipherTextException ex) {
        throw new IllegalArgumentException(ex);
    }
}
 
Example #2
Source File: RLPxConnectionFactory.java    From incubator-tuweni with Apache License 2.0 6 votes vote down vote up
static Bytes decryptMessage(Bytes msgBytes, SecretKey ourKey) {
  Bytes commonMac = msgBytes.slice(0, 2);
  int size = (commonMac.get(1) & 0xFF) + ((commonMac.get(0) & 0xFF) << 8);
  PublicKey ephemeralPublicKey = PublicKey.fromBytes(msgBytes.slice(3, 64));
  Bytes iv = msgBytes.slice(67, 16);
  Bytes encrypted = msgBytes.slice(83, size - 81);

  EthereumIESEncryptionEngine decryptor = forDecryption(ourKey, ephemeralPublicKey, iv, commonMac);
  byte[] result;
  try {
    result = decryptor.processBlock(encrypted.toArrayUnsafe(), 0, encrypted.size());
  } catch (InvalidCipherTextException e) {
    throw new InvalidMACException(e);
  }
  return Bytes.wrap(result);
}
 
Example #3
Source File: RLPxConnectionFactory.java    From cava with Apache License 2.0 6 votes vote down vote up
static Bytes encryptMessage(Bytes message, PublicKey remoteKey) {
  byte[] ivb = new byte[16];
  random.nextBytes(ivb);
  Bytes iv = Bytes.wrap(ivb);
  KeyPair ephemeralKeyPair = KeyPair.random();
  Bytes bytes = addPadding(message);
  int size = bytes.size() + 65 + 16 + 32;
  Bytes sizePrefix = Bytes.of((byte) (size >>> 8), (byte) size);
  EthereumIESEncryptionEngine engine = forEncryption(remoteKey, iv, sizePrefix, ephemeralKeyPair);
  byte[] encrypted;
  try {
    encrypted = engine.processBlock(bytes.toArrayUnsafe(), 0, bytes.size());
  } catch (InvalidCipherTextException e) {
    throw new IllegalArgumentException(e);
  }
  // Create the output message by concatenating the ephemeral public key (prefixed with
  // 0x04 to designate uncompressed), IV, and encrypted bytes.
  Bytes finalBytes = concatenate(
      Bytes.of(sizePrefix.get(0), sizePrefix.get(1), (byte) 0x04),
      ephemeralKeyPair.publicKey().bytes(),
      iv,
      Bytes.wrap(encrypted));
  return finalBytes;
}
 
Example #4
Source File: RLPxConnectionFactory.java    From cava with Apache License 2.0 6 votes vote down vote up
static Bytes decryptMessage(Bytes msgBytes, SecretKey ourKey) {
  Bytes commonMac = msgBytes.slice(0, 2);
  int size = (commonMac.get(1) & 0xFF) + ((commonMac.get(0) & 0xFF) << 8);
  PublicKey ephemeralPublicKey = PublicKey.fromBytes(msgBytes.slice(3, 64));
  Bytes iv = msgBytes.slice(67, 16);
  Bytes encrypted = msgBytes.slice(83, size - 81);

  EthereumIESEncryptionEngine decryptor = forDecryption(ourKey, ephemeralPublicKey, iv, commonMac);
  byte[] result;
  try {
    result = decryptor.processBlock(encrypted.toArrayUnsafe(), 0, encrypted.size());
  } catch (InvalidCipherTextException e) {
    throw new InvalidMACException(e);
  }
  return Bytes.wrap(result);
}
 
Example #5
Source File: AESCBC.java    From InflatableDonkey with MIT License 6 votes vote down vote up
public static byte[] decryptAESCBC(byte[] key, byte[] iv, byte[] data) {
    // AES CBC PKCS7 decrypt
    try {
        CipherParameters cipherParameters = new ParametersWithIV(new KeyParameter(key), iv);
        PaddedBufferedBlockCipher cipher
                = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()), new PKCS7Padding());
        cipher.init(false, cipherParameters);

        byte[] buffer = new byte[cipher.getOutputSize(data.length)];

        int pos = cipher.processBytes(data, 0, data.length, buffer, 0);
        pos += cipher.doFinal(buffer, pos);

        return Arrays.copyOf(buffer, pos);

    } catch (DataLengthException | IllegalStateException | InvalidCipherTextException ex) {
        throw new IllegalArgumentException("decrypt failed", ex);
    }
}
 
Example #6
Source File: SM2.java    From julongchain with Apache License 2.0 6 votes vote down vote up
/**
 * 私钥解密
 *
 * @param encryptData
 * @param privateKey
 * @return
 */
public byte[] decrypt(byte[] encryptData, byte[] privateKey) throws CspException{
    if (null == privateKey) {
        throw new CspException("privateKey is null");
    }
    if (privateKey.length == 0) {
        throw new CspException("privateKey's length is 0");
    }
    if (null==encryptData) {
        throw new CspException("plainText is null");
    }
    if (encryptData.length == 0) {
        throw new CspException("plainText's length is 0");
    }
    SM2Engine sm2Engine = new SM2Engine();
    BigInteger d = byte2BigInteger(privateKey);
    ECPrivateKeyParameters privateKeyParameters = new ECPrivateKeyParameters(d, ecc_bc_spec);
    sm2Engine.init(false, privateKeyParameters);
    try {
        byte[] dec = sm2Engine.processBlock(encryptData, 0, encryptData.length);
        return dec;
    } catch (InvalidCipherTextException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example #7
Source File: BouncyCastleV1CryptoProvider.java    From paseto with MIT License 6 votes vote down vote up
@Override
public byte[] aes256CtrEncrypt(byte[] m, byte[] key, byte[] iv) {
	validateAes256CtrEncrypt(m, key, iv);

	try {
		BufferedBlockCipher cipher = ase256CtrCipher(true, key, iv);

		byte[] cipherText = new byte[cipher.getOutputSize(m.length)];
		int len = cipher.processBytes(m, 0, m.length, cipherText, 0);
		cipher.doFinal(cipherText, len);

		return cipherText;
	} catch (InvalidCipherTextException e) {
		// Not possible since we're not using padding.
		throw new CryptoProviderException("Invalid cipher text in aes256CtrEncrypt.", e);
	}
}
 
Example #8
Source File: BurstCryptoImpl.java    From burstkit4j with Apache License 2.0 6 votes vote down vote up
@Override
public byte[] aesDecrypt(byte[] encrypted, byte[] signingKey, byte[] nonce) {
    if (signingKey.length != 32) {
        throw new IllegalArgumentException("Key length must be 32 bytes");
    }
    try {
        if (encrypted.length < 16 || encrypted.length % 16 != 0) {
            throw new InvalidCipherTextException("invalid ciphertext");
        }
        byte[] iv = Arrays.copyOfRange(encrypted, 0, 16);
        byte[] ciphertext = Arrays.copyOfRange(encrypted, 16, encrypted.length);
        for (int i = 0; i < 32; i++) {
            signingKey[i] ^= nonce[i];
        }
        byte[] key = getSha256().digest(signingKey);
        PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()));
        CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv);
        aes.init(false, ivAndKey);
        byte[] output = new byte[aes.getOutputSize(ciphertext.length)];
        int plaintextLength = aes.processBytes(ciphertext, 0, ciphertext.length, output, 0);
        plaintextLength += aes.doFinal(output, plaintextLength);
        byte[] result = new byte[plaintextLength];
        System.arraycopy(output, 0, result, 0, result.length);
        return result;
    } catch (InvalidCipherTextException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
 
Example #9
Source File: BurstCryptoImpl.java    From burstkit4j with Apache License 2.0 6 votes vote down vote up
@Override
public byte[] aesEncrypt(byte[] plaintext, byte[] signingKey, byte[] nonce) {
    if (signingKey.length != 32) {
        throw new IllegalArgumentException("Key length must be 32 bytes");
    }
    try {
        for (int i = 0; i < 32; i++) {
            signingKey[i] ^= nonce[i];
        }
        byte[] key = getSha256().digest(signingKey);
        byte[] iv = new byte[16];
        secureRandom.nextBytes(iv);
        PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()));
        CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv);
        aes.init(true, ivAndKey);
        byte[] output = new byte[aes.getOutputSize(plaintext.length)];
        int ciphertextLength = aes.processBytes(plaintext, 0, plaintext.length, output, 0);
        ciphertextLength += aes.doFinal(output, ciphertextLength);
        byte[] result = new byte[iv.length + ciphertextLength];
        System.arraycopy(iv, 0, result, 0, iv.length);
        System.arraycopy(output, 0, result, iv.length, ciphertextLength);
        return result;
    } catch (InvalidCipherTextException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
 
Example #10
Source File: AESEngineNoPadding.java    From sambox with Apache License 2.0 6 votes vote down vote up
@Override
public byte[] encryptBytes(byte[] data, byte[] key, byte[] iv)
{
    init(key, iv);
    try
    {
        byte[] buf = new byte[cipher.getOutputSize(data.length)];
        int len = cipher.processBytes(data, 0, data.length, buf, 0);
        len += cipher.doFinal(buf, len);
        return copyOf(buf, len);
    }
    catch (DataLengthException | IllegalStateException | InvalidCipherTextException e)
    {
        throw new EncryptionException(e);
    }
}
 
Example #11
Source File: Main.java    From mremoteng-decrypt with GNU Affero General Public License v3.0 6 votes vote down vote up
public static byte[] decryptAEADgcm(byte[] password, byte[] nonce, byte[] cipherText, byte[]associatedText){
    KeyParameter pwdparam = new KeyParameter(password);
    AEADParameters aeadpm = new AEADParameters(pwdparam, MacBitSize, nonce, associatedText);
    GCMBlockCipher gcmcipher = new GCMBlockCipher(new AESEngine());
    gcmcipher.init(false, aeadpm);
    byte[] plainBytes = new byte[gcmcipher.getOutputSize(cipherText.length)];
    int retLen = gcmcipher.processBytes(cipherText, 0, cipherText.length, plainBytes,0);
    try {
        gcmcipher.doFinal(plainBytes, retLen);
    } catch (InvalidCipherTextException e) {
        e.printStackTrace();
        System.out.println("\n Error Occured While Trying to Decrypt the AES-128-GCM. \n");
        System.exit(2);
    }
    return plainBytes;
}
 
Example #12
Source File: BouncyCastleV1CryptoProvider.java    From paseto with MIT License 6 votes vote down vote up
@Override
public byte[] aes256CtrDecrypt(byte[] c, byte[] key, byte[] iv) {
	validateAes256CtrDecrypt(c, key, iv);

	try {
		BufferedBlockCipher cipher = ase256CtrCipher(false, key, iv);

		byte[] clearText = new byte[cipher.getOutputSize(c.length)];
		int len = cipher.processBytes(c, 0, c.length, clearText, 0);
		cipher.doFinal(clearText, len);

		return clearText;
	} catch (InvalidCipherTextException e) {
		// Not possible since we're not using padding.
		throw new CryptoProviderException("Invalid cipher text in aes256CtrDecrypt.", e);
	}
}
 
Example #13
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 #14
Source File: EncryptedMessage.java    From besu with Apache License 2.0 6 votes vote down vote up
/**
 * Decrypts the ciphertext using our private key.
 *
 * @param msgBytes The ciphertext.
 * @param nodeKey Abstraction of this nodes private key & associated cryptographic operations
 * @return The plaintext.
 * @throws InvalidCipherTextException Thrown if decryption failed.
 */
public static Bytes decryptMsg(final Bytes msgBytes, final NodeKey nodeKey)
    throws InvalidCipherTextException {

  // Extract the ephemeral public key, stripping off the first byte (0x04), which designates it's
  // an uncompressed key.
  final SECP256K1.PublicKey ephPubKey = SECP256K1.PublicKey.create(msgBytes.slice(1, 64));

  // Strip off the IV to use.
  final Bytes iv = msgBytes.slice(65, IV_SIZE);

  // Extract the encrypted payload.
  final Bytes encrypted = msgBytes.slice(65 + IV_SIZE);

  // Perform the decryption.
  final ECIESEncryptionEngine decryptor =
      ECIESEncryptionEngine.forDecryption(nodeKey, ephPubKey, iv);
  return decryptor.decrypt(encrypted);
}
 
Example #15
Source File: EncryptedMessage.java    From besu with Apache License 2.0 6 votes vote down vote up
/**
 * Encrypts a message for the specified peer using ECIES.
 *
 * @param bytes The plaintext.
 * @param remoteKey The peer's remote key.
 * @return The ciphertext.
 * @throws InvalidCipherTextException Thrown if encryption failed.
 */
public static Bytes encryptMsg(final Bytes bytes, final SECP256K1.PublicKey remoteKey)
    throws InvalidCipherTextException {
  // TODO: check size.
  final ECIESEncryptionEngine engine = ECIESEncryptionEngine.forEncryption(remoteKey);

  // Do the encryption.
  final Bytes encrypted = engine.encrypt(bytes);
  final Bytes iv = engine.getIv();
  final SECP256K1.PublicKey ephPubKey = engine.getEphPubKey();

  // Create the output message by concatenating the ephemeral public key (prefixed with
  // 0x04 to designate uncompressed), IV, and encrypted bytes.
  final MutableBytes answer =
      MutableBytes.create(1 + ECIESHandshaker.PUBKEY_LENGTH + IV_SIZE + encrypted.size());

  int offset = 0;
  // Set the first byte as 0x04 to specify it's an uncompressed key.
  answer.set(offset, (byte) 0x04);
  ephPubKey.getEncodedBytes().copyTo(answer, offset += 1);
  iv.copyTo(answer, offset += ECIESHandshaker.PUBKEY_LENGTH);
  encrypted.copyTo(answer, offset + iv.size());
  return answer;
}
 
Example #16
Source File: EncryptedMessage.java    From besu with Apache License 2.0 6 votes vote down vote up
/**
 * Decrypts the ciphertext using our private key.
 *
 * @param msgBytes The ciphertext.
 * @param nodeKey Abstraction of this nodes private key & associated cryptographic operations
 * @return The plaintext.
 * @throws InvalidCipherTextException Thrown if decryption failed.
 */
public static Bytes decryptMsgEIP8(final Bytes msgBytes, final NodeKey nodeKey)
    throws InvalidCipherTextException {
  final SECP256K1.PublicKey ephPubKey = SECP256K1.PublicKey.create(msgBytes.slice(3, 64));

  // Strip off the IV to use.
  final Bytes iv = msgBytes.slice(3 + 64, IV_SIZE);

  // Extract the encrypted payload.
  final Bytes encrypted = msgBytes.slice(3 + 64 + IV_SIZE);

  // Perform the decryption.
  final ECIESEncryptionEngine decryptor =
      ECIESEncryptionEngine.forDecryption(nodeKey, ephPubKey, iv);
  return decryptor.decrypt(encrypted, msgBytes.slice(0, 2).toArray());
}
 
Example #17
Source File: FileKeyFactory.java    From LiquidDonkey with MIT License 5 votes vote down vote up
ByteString unwrapCurve25519(KeyBag keyBag, int protectionClass, ByteString key, AESWrap aesWrap, SHA256Digest sha256) {
    if (key.size() != 0x48) {
        logger.warn("-- unwrapCurve25519() > bad key length: {}", Bytes.hex(key));
        return null;
    }

    byte[] myPrivateKey = keyBag.classKey(protectionClass, "KEY").toByteArray();
    if (myPrivateKey == null) {
        logger.warn("-- unwrapCurve25519() > no KEY key for protection class: {}", protectionClass);
        return null;
    }

    byte[] myPublicKey = keyBag.classKey(protectionClass, "PBKY").toByteArray();
    if (myPublicKey == null) {
        logger.warn("-- unwrapCurve25519() > no PBKY key for protection class: {}", protectionClass);
        return null;
    }

    byte[] otherPublicKey = key.substring(0, 32).toByteArray();
    byte[] shared = Curve25519.create().agreement(otherPublicKey, myPrivateKey);
    byte[] pad = new byte[]{0x00, 0x00, 0x00, 0x01};
    byte[] hash = new byte[sha256.getDigestSize()];

    sha256.reset();
    sha256.update(pad, 0, pad.length);
    sha256.update(shared, 0, shared.length);
    sha256.update(otherPublicKey, 0, otherPublicKey.length);
    sha256.update(myPublicKey, 0, myPublicKey.length);
    sha256.doFinal(hash, 0);

    try {
        return ByteString.copyFrom(aesWrap.unwrap(hash, key.substring(0x20, key.size()).toByteArray()));
    } catch (IllegalStateException | InvalidCipherTextException ex) {
        logger.warn("-- unwrapCurve25519() > failed to unwrap key: {} protection class: {} exception: {}",
                Bytes.hex(key), protectionClass, ex);
        return null;
    }
}
 
Example #18
Source File: EncryptMessageTest.java    From COSE-JAVA with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void encryptBadIV() throws CoseException, InvalidCipherTextException, Exception {
    EncryptMessage msg = new EncryptMessage();
    msg.addRecipient(recipient128);
    
    thrown.expect(CoseException.class);
    thrown.expectMessage("IV is incorrectly formed");
    msg.addAttribute(HeaderKeys.Algorithm, AlgorithmID.AES_GCM_128.AsCBOR(), Attribute.PROTECTED);
    msg.addAttribute(HeaderKeys.IV, CBORObject.FromObject("IV"), Attribute.UNPROTECTED);
    msg.SetContent(rgbContent);
    msg.encrypt();
}
 
Example #19
Source File: SoftKeymasterBlob.java    From keystore-decryptor with Apache License 2.0 5 votes vote down vote up
public static ECPrivateKey parseEcKey(byte[] blob) throws GeneralSecurityException,
        IOException, InvalidCipherTextException {
    ASN1InputStream ain = new ASN1InputStream(new ByteArrayInputStream(
            blob));
    org.bouncycastle.asn1.sec.ECPrivateKey pk = org.bouncycastle.asn1.sec.ECPrivateKey
            .getInstance(ain.readObject());
    ain.close();

    return toJcaPrivateKey(pk);
}
 
Example #20
Source File: SoftKeymasterBlob.java    From keystore-decryptor with Apache License 2.0 5 votes vote down vote up
private void parsePrivateKey(byte[] privKeyBytes)
        throws GeneralSecurityException,
        IOException, InvalidCipherTextException {
    if (type == EVP_PKEY_EC) {
        privateKey = parseEcKey(privKeyBytes);
        publicKey = null;
    } else if (type == EVP_PKEY_DSA) {
        parseDsaKeyPair(privKeyBytes);
    } else if (type == EVP_PKEY_RSA) {
        parseRsaKeyPair(privKeyBytes);
    } else {
        throw new IllegalStateException("Unknown soft KM blob type: " + type);
    }
}
 
Example #21
Source File: AESGCMEncryptor.java    From archistar-smc with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public byte[] decrypt(byte[] data, byte[] randomKey)
        throws InvalidKeyException, InvalidAlgorithmParameterException, IOException,
        IllegalStateException, InvalidCipherTextException {

    AEADBlockCipher cipher = new GCMBlockCipher(new AESFastEngine());
    cipher.init(false, new AEADParameters(new KeyParameter(randomKey), 128, randomIvBytes));
    return cipherData(cipher, data);
}
 
Example #22
Source File: ChaCha20Encryptor.java    From archistar-smc with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public byte[] encrypt(byte[] data, byte[] randomKeyBytes) throws IOException, InvalidKeyException,
        InvalidAlgorithmParameterException, InvalidCipherTextException {

    ChaChaEngine cipher = new ChaChaEngine();
    cipher.init(true, new ParametersWithIV(new KeyParameter(randomKeyBytes), randomIvBytes));

    byte[] result = new byte[data.length];
    cipher.processBytes(data, 0, data.length, result, 0);
    return result;
}
 
Example #23
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 #24
Source File: EncryptMessageTest.java    From COSE-JAVA with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void encryptIncorrectIV() throws CoseException, InvalidCipherTextException, Exception {
    EncryptMessage msg = new EncryptMessage();
    msg.addRecipient(recipient128);
    
    thrown.expect(CoseException.class);
    thrown.expectMessage("IV size is incorrect");
    msg.addAttribute(HeaderKeys.Algorithm, AlgorithmID.AES_GCM_128.AsCBOR(), Attribute.PROTECTED);
    msg.addAttribute(HeaderKeys.IV, rgbIV128, Attribute.UNPROTECTED);
    msg.SetContent(rgbContent);
    msg.encrypt();
}
 
Example #25
Source File: EncryptionUtilTest.java    From Hive2Hive with MIT License 5 votes vote down vote up
@Test
@Ignore
public void testPureLightweightBouncyCastle() throws IOException, InvalidKeyException, IllegalBlockSizeException,
		BadPaddingException, DataLengthException, IllegalStateException, InvalidCipherTextException,
		NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidAlgorithmParameterException {

	long startTime = System.currentTimeMillis();

	Security.addProvider(new BouncyCastleProvider());

	// generate RSA keys
	RSAKeyPairGenerator gen = new RSAKeyPairGenerator();
	gen.init(new RSAKeyGenerationParameters(new BigInteger("10001", 16), new SecureRandom(), 2048, 80));
	AsymmetricCipherKeyPair keyPair = gen.generateKeyPair();

	// some data where first entry is 0
	byte[] data = { 10, 122, 12, 127, 35, 58, 87, 56, -6, 73, 10, -13, -78, 4, -122, -61 };

	// encrypt data asymmetrically
	AsymmetricBlockCipher cipher = new RSAEngine();
	cipher = new PKCS1Encoding(cipher);
	cipher.init(true, keyPair.getPublic());
	byte[] rsaEncryptedData = cipher.processBlock(data, 0, data.length);

	Assert.assertFalse(Arrays.equals(data, rsaEncryptedData));

	// decrypt data asymmetrically
	cipher.init(false, keyPair.getPrivate());
	byte[] dataBack = cipher.processBlock(rsaEncryptedData, 0, rsaEncryptedData.length);

	assertTrue(Arrays.equals(data, dataBack));

	long stopTime = System.currentTimeMillis();
	long elapsedTime = stopTime - startTime;
	logger.debug("elapsed time = {}", elapsedTime);
}
 
Example #26
Source File: EncryptMessageTest.java    From COSE-JAVA with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void encryptNoRecipients() throws CoseException, InvalidCipherTextException, Exception {
    EncryptMessage msg = new EncryptMessage();
    
    thrown.expect(CoseException.class);
    thrown.expectMessage("No recipients supplied");
    msg.addAttribute(HeaderKeys.Algorithm, AlgorithmID.AES_GCM_128.AsCBOR(), Attribute.PROTECTED);
    msg.SetContent(rgbContent);
    msg.encrypt();
}
 
Example #27
Source File: EncryptMessageTest.java    From COSE-JAVA with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void encryptNoAlgorithm() throws CoseException, InvalidCipherTextException, Exception {
    EncryptMessage msg = new EncryptMessage();
    msg.addRecipient(recipient128);
    
    thrown.expect(CoseException.class);
    thrown.expectMessage("No Algorithm Specified");
    msg.SetContent(rgbContent);
    msg.encrypt();
}
 
Example #28
Source File: EncryptMessageTest.java    From COSE-JAVA with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void encryptUnknownAlgorithm() throws CoseException, InvalidCipherTextException, Exception {
    EncryptMessage msg = new EncryptMessage();
    msg.addRecipient(recipient128);
    
    thrown.expect(CoseException.class);
    thrown.expectMessage("Unknown Algorithm Specified");
    msg.addAttribute(HeaderKeys.Algorithm, CBORObject.FromObject("Unknown"), Attribute.PROTECTED);
    msg.SetContent(rgbContent);
    msg.encrypt();
}
 
Example #29
Source File: EncryptMessageTest.java    From COSE-JAVA with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void encryptUnsupportedAlgorithm() throws CoseException, InvalidCipherTextException, Exception {
    EncryptMessage msg = new EncryptMessage();
    msg.addRecipient(recipient128);
    
    thrown.expect(CoseException.class);
    thrown.expectMessage("Unsupported Algorithm Specified");
    msg.addAttribute(HeaderKeys.Algorithm, AlgorithmID.HMAC_SHA_256.AsCBOR(), Attribute.PROTECTED);
    msg.SetContent(rgbContent);
    msg.encrypt();
}
 
Example #30
Source File: EncryptMessageTest.java    From COSE-JAVA with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void encryptNoContent() throws CoseException, InvalidCipherTextException, Exception {
    EncryptMessage msg = new EncryptMessage();
    msg.addRecipient(recipient128);
    
    thrown.expect(CoseException.class);
    thrown.expectMessage("No Content Specified");
    msg.addAttribute(HeaderKeys.Algorithm, AlgorithmID.AES_GCM_128.AsCBOR(), Attribute.PROTECTED);
    msg.encrypt();
}