org.bouncycastle.crypto.DataLengthException Java Examples

The following examples show how to use org.bouncycastle.crypto.DataLengthException. 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: 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 #2
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 #3
Source File: DPAESCBCCipher.java    From InflatableDonkey with MIT License 6 votes vote down vote up
@Override
public int processBlock(byte[] in, int inOff, byte[] out, int outOff) throws DataLengthException, IllegalStateException {
    if (key == null) {
        throw new IllegalStateException("not initialised");
    }

    if (offset == 0) {
        byte[] iv = ivGenerator.apply(index);
        ParametersWithIV parameters = new ParametersWithIV(key, iv);
        cipher.init(forEncryption, parameters);
    }

    offset += getBlockSize();
    if (offset == blockLength) {
        index++;
        offset = 0;
    }
    return cipher.processBlock(in, inOff, out, outOff);
}
 
Example #4
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 #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: XTSAESCipher.java    From InflatableDonkey with MIT License 6 votes vote down vote up
int process(byte[] in, int inOff, int length, byte[] out, int outOff)
        throws DataLengthException, IllegalStateException {
    if (length < blockSize) {
        throw new DataLengthException("data unit size too small: " + length);
    }
    if (inOff + length > in.length) {
        throw new DataLengthException("input buffer too small for data unit size: " + length);
    }
    if (outOff + length > out.length) {
        throw new DataLengthException("output buffer too small for data unit size: " + length);
    }
    int to = length % blockSize == 0 ? length : length - (blockSize * 2);

    int i;
    for (i = 0; i < to; i += blockSize) {
        core.processBlock(in, inOff + i, out, outOff + i);
    }
    if (length > i) {
        core.processPartial(in, inOff + i, out, outOff + i, length - i);
    }
    return length;
}
 
Example #7
Source File: Metodos.java    From ExamplesAndroid with Apache License 2.0 5 votes vote down vote up
public String testDecryptRijndael(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(false, new KeyParameter(keyBytes));

        byte[] output = Base64.decode(value.getBytes());
        byte[] cipherText = new byte[cipher.getOutputSize(output.length)];

        int cipherLength = cipher.processBytes(output, 0, output.length, cipherText, 0);
        int outputLength = cipher.doFinal(cipherText, cipherLength);
        outputLength += cipherLength;

        byte[] resultBytes = cipherText;
        if (outputLength != output.length) {
            resultBytes = new byte[outputLength];
            System.arraycopy(
                    cipherText, 0,
                    resultBytes, 0,
                    outputLength
            );
        }

        String result = new String(resultBytes);
return  result;
    }
 
Example #8
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 #9
Source File: BCStrongAESEncryption.java    From Hive2Hive with MIT License 5 votes vote down vote up
@Override
public byte[] decryptStrongAES(byte[] data, SecretKey key, byte[] initVector) throws GeneralSecurityException {
	try {
		return processAESCipher(false, data, key, initVector);
	} catch (DataLengthException | IllegalStateException | InvalidCipherTextException e) {
		throw new GeneralSecurityException("Cannot decrypt the data with AES 256bit", e);
	}
}
 
Example #10
Source File: BCStrongAESEncryption.java    From Hive2Hive with MIT License 5 votes vote down vote up
@Override
public byte[] encryptStrongAES(byte[] data, SecretKey key, byte[] initVector) throws GeneralSecurityException {
	try {
		return processAESCipher(true, data, key, initVector);
	} catch (DataLengthException | IllegalStateException | InvalidCipherTextException e) {
		throw new GeneralSecurityException("Cannot encrypt the data with AES 256bit", e);
	}
}
 
Example #11
Source File: NativeRSACoreEngine.java    From jna-gmp with Apache License 2.0 5 votes vote down vote up
public BigInteger convertInput(
    byte[]  in,
    int     inOff,
    int     inLen)
{
    if (inLen > (getInputBlockSize() + 1))
    {
        throw new DataLengthException("input too large for RSA cipher.");
    }
    else if (inLen == (getInputBlockSize() + 1) && !forEncryption)
    {
        throw new DataLengthException("input too large for RSA cipher.");
    }

    byte[]  block;

    if (inOff != 0 || inLen != in.length)
    {
        block = new byte[inLen];

        System.arraycopy(in, inOff, block, 0, inLen);
    }
    else
    {
        block = in;
    }

    BigInteger res = new BigInteger(1, block);
    if (res.compareTo(key.getModulus()) >= 0)
    {
        throw new DataLengthException("input too large for RSA cipher.");
    }

    return res;
}
 
Example #12
Source File: ChunkDecrypter.java    From LiquidDonkey with MIT License 5 votes vote down vote up
byte[] decrypt(ChunkServer.ChunkInfo chunkInfo, byte[] data, int offset) throws BadDataException {
    try {
        if (!chunkInfo.hasChunkEncryptionKey()) {
            throw new BadDataException("Missing key");
        }

        if (keyType(chunkInfo) != 1) {
            throw new BadDataException("Unknown key type: " + keyType(chunkInfo));
        }

        byte[] decrypted = decryptCfbAes(chunkInfo, data, offset);

        if (chunkInfo.hasChunkChecksum()) {
            if (!checksum(chunkInfo).equals(checksum(decrypted))) {
                logger.debug("-- decrypt() >  checksum failed: {} expected: {}",
                        Bytes.hex(checksum(decrypted)), Bytes.hex(checksum(chunkInfo)));
                throw new BadDataException("Decrypt bad checksum");
            }
        } else {
            logger.warn("-- decrypt() >  missing chunk info checksum, unable to verify data integrity");
        }

        return decrypted;
    } catch (DataLengthException | ArrayIndexOutOfBoundsException | NullPointerException ex) {
        throw new BadDataException("Decrypt failed", ex);
    }
}
 
Example #13
Source File: StandardSecurityHandler.java    From sambox with Apache License 2.0 5 votes vote down vote up
private void validatePerms(PDEncryption encryption, int dicPermissions, boolean encryptMetadata)
        throws IOException
{
    try
    {
        BufferedBlockCipher cipher = new BufferedBlockCipher(new AESFastEngine());
        cipher.init(false, new KeyParameter(getEncryptionKey()));

        byte[] buf = new byte[cipher.getOutputSize(encryption.getPerms().length)];
        int len = cipher.processBytes(encryption.getPerms(), 0, encryption.getPerms().length,
                buf, 0);
        len += cipher.doFinal(buf, len);
        byte[] perms = copyOf(buf, len);

        if (perms[9] != 'a' || perms[10] != 'd' || perms[11] != 'b')
        {
            LOG.warn("Verification of permissions failed (constant)");
        }

        int permsP = perms[0] & 0xFF | (perms[1] & 0xFF) << 8 | (perms[2] & 0xFF) << 16
                | (perms[3] & 0xFF) << 24;

        if (permsP != dicPermissions)
        {
            LOG.warn("Verification of permissions failed (" + String.format("%08X", permsP)
                    + " != " + String.format("%08X", dicPermissions) + ")");
        }

        if (encryptMetadata && perms[8] != 'T' || !encryptMetadata && perms[8] != 'F')
        {
            LOG.warn("Verification of permissions failed (EncryptMetadata)");
        }
    }
    catch (DataLengthException | IllegalStateException | InvalidCipherTextException e)
    {
        throw new IOException(e);
    }
}
 
Example #14
Source File: XTSAESBlockCipher.java    From InflatableDonkey with MIT License 5 votes vote down vote up
@Override
public int processBlock(byte[] in, int inOff, byte[] out, int outOff)
        throws DataLengthException, IllegalStateException {
    if (index == 0) {
        core.reset(dataUnit);
    }
    if ((index += blockSize) == dataUnitSize) {
        dataUnit++;
        index = 0;
    }
    return core.processBlock(in, inOff, out, outOff);
}
 
Example #15
Source File: XTSCore.java    From InflatableDonkey with MIT License 5 votes vote down vote up
int doProcessPartial(byte[] in, int inOff, byte[] out, int outOff, int length, byte[] tweakA, byte[] tweakB)
        throws DataLengthException, IllegalStateException {
    // M-1 block
    doProcessBlock(in, inOff, out, outOff, tweakA);
    // Cipher stealing
    byte[] buffer = Arrays.copyOfRange(out, outOff, outOff + BLOCK_SIZE);
    System.arraycopy(in, inOff + BLOCK_SIZE, buffer, 0, length - BLOCK_SIZE);
    // M block
    doProcessBlock(buffer, 0, buffer, 0, tweakB);
    // Copy blocks
    System.arraycopy(out, outOff, out, outOff + BLOCK_SIZE, length - BLOCK_SIZE);
    System.arraycopy(buffer, 0, out, outOff, BLOCK_SIZE);
    return length;
}
 
Example #16
Source File: XTSCore.java    From InflatableDonkey with MIT License 5 votes vote down vote up
int processPartial(byte[] in, int inOff, byte[] out, int outOff, int length) {
    if (length <= BLOCK_SIZE) {
        throw new DataLengthException("input buffer too small/ missing last two blocks: " + length);
    }
    if (length >= BLOCK_SIZE * 2) {
        throw new DataLengthException("input buffer too large/ non-partial final block: " + length);
    }
    byte[] tweakA = tweak.value();
    byte[] tweakB = tweak.next().value();
    return forEncryption
            ? doProcessPartial(in, inOff, out, outOff, length, tweakA, tweakB)
            : doProcessPartial(in, inOff, out, outOff, length, tweakB, tweakA);
}
 
Example #17
Source File: XTSCore.java    From InflatableDonkey with MIT License 5 votes vote down vote up
int doProcessBlock(byte[] in, int inOff, byte[] out, int outOff, byte[] tweakValue)
        throws DataLengthException, IllegalStateException {
    merge(in, inOff, out, outOff, tweakValue);
    cipher.processBlock(out, outOff, out, outOff);
    merge(out, outOff, out, outOff, tweakValue);
    return BLOCK_SIZE;
}
 
Example #18
Source File: KeyCodecTest.java    From UAF with Apache License 2.0 5 votes vote down vote up
@Test
public void pssDER() throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException, DataLengthException, CryptoException, InvalidKeyException, SignatureException, InvalidKeySpecException, IOException{
	KeyPair keyPair = KeyCodec.getRSAKeyPair();
	KeyPair keyPair2 = KeyCodec.getRSAKeyPair();
	
	PrivateKey privKey = keyPair.getPrivate();
	byte[] encodedPrivKey = privKey.getEncoded();
	logger.info("priv=" + Base64.encodeBase64URLSafeString(encodedPrivKey));

	PublicKey pubKey = keyPair.getPublic();
	byte[] encodedPubKey = pubKey.getEncoded();
	
	logger.info("pub=" + Base64.encodeBase64URLSafeString(encodedPubKey));
	logger.info("pub format=" + pubKey.getFormat());
	logger.info("pub alg=" + pubKey.getAlgorithm());
	
	byte[] slt = Hex.decode("dee959c7e06411361420ff80185ed57f3e6776af"); //a random salt
	
	byte[] signed = RSA.signPSS(privKey, slt);
	
	assertTrue(signed.length>0);
	RSA rsa = new RSA();
	Assert.assertTrue(rsa.verifyPSS(pubKey, slt, signed));
	byte[] slt2 = Hex.decode("dee959c7e06411361420ff80185ed57f3e6776aa"); //a random salt  
	
	byte[] signed2 = RSA.signPSS(keyPair2.getPrivate(), slt2);
	Assert.assertFalse(rsa.verifyPSS(pubKey, slt2, signed2));
	Assert.assertFalse(rsa.verifyPSS(keyPair2.getPublic(), slt, signed));
}
 
Example #19
Source File: KeyCodecTest.java    From UAF with Apache License 2.0 5 votes vote down vote up
@Test
public void pss() throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException, DataLengthException, CryptoException, InvalidKeyException, SignatureException, InvalidKeySpecException, IOException{
	KeyPair keyPair = KeyCodec.getRSAKeyPair();
	KeyPair keyPair2 = KeyCodec.getRSAKeyPair();
	
	PrivateKey privKey = keyPair.getPrivate();
	byte[] encodedPrivKey = privKey.getEncoded();
	logger.info("priv=" + Base64.encodeBase64URLSafeString(encodedPrivKey));

	PublicKey pubKey = keyPair.getPublic();
	byte[] encodedPubKey = pubKey.getEncoded();
	SubjectPublicKeyInfo spkInfo = SubjectPublicKeyInfo.getInstance(encodedPubKey);
	ASN1Primitive primitive = spkInfo.parsePublicKey();
	
	PublicKey publicKey = KeyCodec.getRSAPublicKey(primitive.getEncoded());
	logger.info("pub=" + Base64.encodeBase64URLSafeString(encodedPubKey));
	logger.info("pub format=" + pubKey.getFormat());
	logger.info("pub alg=" + pubKey.getAlgorithm());
	
	byte[] slt = Hex.decode("dee959c7e06411361420ff80185ed57f3e6776af"); //a random salt
	
	byte[] signed = RSA.signPSS(privKey, slt);
	assertTrue(signed.length>0);
	RSA rsa = new RSA();
	Assert.assertTrue(rsa.verifyPSS(publicKey, slt, signed));
	byte[] slt2 = Hex.decode("dee959c7e06411361420ff80185ed57f3e6776aa"); //a random salt  
	
	byte[] signed2 = RSA.signPSS(keyPair2.getPrivate(), slt2);
	Assert.assertFalse(rsa.verifyPSS(publicKey, slt2, signed2));
	Assert.assertFalse(rsa.verifyPSS(keyPair2.getPublic(), slt, signed));
}
 
Example #20
Source File: XTSAESCipher.java    From InflatableDonkey with MIT License 4 votes vote down vote up
public int processDataUnit(byte[] in, int inOff, int length, byte[] out, int outOff, long sequenceNumber)
        throws DataLengthException, IllegalStateException {
    core.reset(sequenceNumber);
    return process(in, inOff, length, out, outOff);
}
 
Example #21
Source File: XTSTweak.java    From InflatableDonkey with MIT License 4 votes vote down vote up
XTSTweak reset(byte[] tweakBytes) throws DataLengthException, IllegalStateException {
    cipher.processBlock(tweakBytes, 0, tweak, 0);
    return this;
}
 
Example #22
Source File: FileAssembler.java    From InflatableDonkey with MIT License 4 votes vote down vote up
boolean write(Path path,
        String info,
        List<Chunk> chunks, Optional<XFileKey> keyCipher,
        Optional<byte[]> signature,
        Optional<Integer> compression) {
    logger.debug("-- write() - path: {} key cipher: {} signature: 0x{}",
            path, keyCipher, signature.map(Hex::toHexString).orElse("NULL"));

    boolean status = true;
    Optional<IOFunction<InputStream, InputStream>> decompress;
    if (compression.isPresent()) {
        if (compression.get() == 2) {
            decompress = Optional.of(LZFSEInputStream::new);
        } else {
            logger.warn("-- write() - unsupported compression: {} -> {}", info, compression.get());
            decompress = Optional.empty();
        }
    } else {
        decompress = Optional.empty();
    }

    try (OutputStream out = Files.newOutputStream(path);
            InputStream in = chunkStream(chunks)) {
        status &= FileStreamWriter.copy(in, out, keyCipher, signature, decompress);

        if (keyCipher.isPresent()) {
            XFileKey kc = keyCipher.get();
            logger.debug("-- write() - written: {} status: {} mode: {} flags: 0x{}",
                    path, status, kc.ciphers(), Hex.toHexString(kc.flags()));
            if (!QUIET) {
                System.out.println(">> " + info + " " + kc.ciphers() + " " + Hex.toHexString(kc.flags()));
            }
        } else {
            logger.debug("-- write() - written: {} status: {}", path, status);
            if (!QUIET) {
                System.out.println(">> " + info);
            }
        }
        return status;

    } catch (IOException | DataLengthException | IllegalStateException ex) {
        logger.warn("-- write() - error: ", ex);
        return false;
    }
}
 
Example #23
Source File: XTSTweak.java    From InflatableDonkey with MIT License 4 votes vote down vote up
XTSTweak reset(long tweakValue) throws DataLengthException, IllegalStateException {
    return reset(tweakFunction.apply(tweakValue));
}
 
Example #24
Source File: StandardSecurityHandler.java    From sambox with Apache License 2.0 4 votes vote down vote up
private byte[] computeEncryptedKeyRev56(byte[] password, boolean isOwnerPassword, byte[] o,
        byte[] u, byte[] oe, byte[] ue, int encRevision) throws IOException
{
    byte[] hash, fileKeyEnc;

    if (isOwnerPassword)
    {
        byte[] oKeySalt = new byte[8];
        System.arraycopy(o, 40, oKeySalt, 0, 8);

        if (encRevision == 5)
        {
            hash = computeSHA256(password, oKeySalt, u);
        }
        else
        {
            hash = computeHash2A(password, oKeySalt, u);
        }

        fileKeyEnc = oe;
    }
    else
    {
        byte[] uKeySalt = new byte[8];
        System.arraycopy(u, 40, uKeySalt, 0, 8);

        if (encRevision == 5)
        {
            hash = computeSHA256(password, uKeySalt, null);
        }
        else
        {
            hash = computeHash2A(password, uKeySalt, null);
        }

        fileKeyEnc = ue;
    }
    try
    {
        BufferedBlockCipher cipher = new BufferedBlockCipher(
                new CBCBlockCipher(new AESFastEngine()));
        cipher.init(false, new KeyParameter(hash));
        byte[] buf = new byte[cipher.getOutputSize(fileKeyEnc.length)];
        int len = cipher.processBytes(fileKeyEnc, 0, fileKeyEnc.length, buf, 0);
        len += cipher.doFinal(buf, len);
        return copyOf(buf, len);
    }
    catch (DataLengthException | IllegalStateException | InvalidCipherTextException e)
    {
        throw new IOException(e);
    }
}
 
Example #25
Source File: P11ContentSigner.java    From xipki with Apache License 2.0 4 votes vote down vote up
byte[] generateSignature() throws DataLengthException, CryptoException {
  byte[] signature = pssSigner.generateSignature();
  pssSigner.reset();
  return signature;
}
 
Example #26
Source File: XTSCore.java    From InflatableDonkey with MIT License 4 votes vote down vote up
int processBlock(byte[] in, int inOff, byte[] out, int outOff) throws DataLengthException, IllegalStateException {
    byte[] tweakValue = tweak.value();
    doProcessBlock(in, inOff, out, outOff, tweakValue);
    tweak.next();
    return BLOCK_SIZE;
}
 
Example #27
Source File: XTSCore.java    From InflatableDonkey with MIT License 4 votes vote down vote up
XTSCore reset(long tweakValue) throws DataLengthException, IllegalStateException {
    tweak.reset(tweakValue);
    return this;
}
 
Example #28
Source File: ChangeProtectionKeysStepTest.java    From Hive2Hive with MIT License 4 votes vote down vote up
@Test
public void testStepSuccessAndRollbackWithChunk() throws InterruptedException, NoPeerConnectionException,
		DataLengthException, InvalidKeyException, IllegalStateException, InvalidCipherTextException,
		IllegalBlockSizeException, BadPaddingException, IOException, SignatureException, InvalidProcessStateException,
		ProcessRollbackException {
	// where the process runs
	NetworkManager getter = network.get(0);
	// where the data gets stored
	NetworkManager proxy = network.get(1);

	// generate necessary keys
	KeyPair encryptionKeys = generateRSAKeyPair(H2HConstants.KEYLENGTH_CHUNK);
	KeyPair protectionKeysOld = generateRSAKeyPair(H2HConstants.KEYLENGTH_PROTECTION);
	KeyPair protectionKeysNew = generateRSAKeyPair(H2HConstants.KEYLENGTH_PROTECTION);

	// generate a fake chunk
	Chunk chunk = new Chunk(proxy.getNodeId(), randomString().getBytes(), 0);
	// encrypt the chunk
	HybridEncryptedContent encryptedChunk = dummyEncryption.encryptHybrid(chunk, encryptionKeys.getPublic());

	// initialize put
	Parameters parameters = new Parameters().setLocationKey(chunk.getId()).setContentKey(H2HConstants.FILE_CHUNK)
			.setProtectionKeys(protectionKeysOld).setNetworkContent(encryptedChunk);
	// indicate to generate hash
	parameters.setHashFlag(true);
	// put encrypted chunk into network
	getter.getDataManager().putUnblocked(parameters).awaitUninterruptibly();

	// verify put
	Assert.assertNotNull(getter.getDataManager().getUnblocked(parameters).awaitUninterruptibly().data());

	// initialize a fake process context
	BasePKUpdateContext context = new TestChunkPKUpdateContext(protectionKeysOld, protectionKeysNew, chunk,
			parameters.getHash());
	// create a change protection keys process step
	ChangeProtectionKeysStep step = new ChangeProtectionKeysStep(context, getter.getDataManager());
	// run process, should not fail
	TestExecutionUtil.executeProcessTillSucceded(step);

	// verify if content protection keys have changed
	Assert.assertEquals(protectionKeysNew.getPublic(), getter.getDataManager().getUnblocked(parameters)
			.awaitUninterruptibly().data().publicKey());

	// manually trigger roll back
	step.rollback();

	// verify if content protection keys have changed to old ones
	Assert.assertEquals(protectionKeysOld.getPublic(), getter.getDataManager().getUnblocked(parameters)
			.awaitUninterruptibly().data().publicKey());
}
 
Example #29
Source File: ChangeProtectionKeysStepTest.java    From Hive2Hive with MIT License 4 votes vote down vote up
@Test
public void testStepSuccessAndRollbackWithMetaFile() throws InterruptedException, NoPeerConnectionException,
		DataLengthException, InvalidKeyException, IllegalStateException, InvalidCipherTextException,
		IllegalBlockSizeException, BadPaddingException, IOException, SignatureException, InvalidProcessStateException,
		ProcessRollbackException {
	// where the process runs
	NetworkManager getter = network.get(0);

	// generate necessary keys
	KeyPair chunkEncryptionKeys = generateRSAKeyPair(H2HConstants.KEYLENGTH_CHUNK);
	KeyPair metaFileEncryptionKeys = generateRSAKeyPair(H2HConstants.KEYLENGTH_META_FILE);
	KeyPair protectionKeysOld = generateRSAKeyPair(H2HConstants.KEYLENGTH_PROTECTION);
	KeyPair protectionKeysNew = generateRSAKeyPair(H2HConstants.KEYLENGTH_PROTECTION);

	// generate a fake meta file
	List<MetaChunk> metaChunks1 = new ArrayList<MetaChunk>();
	metaChunks1.add(new MetaChunk(randomString(), randomString().getBytes(), 0));
	metaChunks1.add(new MetaChunk(randomString(), randomString().getBytes(), 1));
	List<MetaChunk> metaChunks2 = new ArrayList<MetaChunk>();
	metaChunks2.add(new MetaChunk(randomString(), randomString().getBytes(), 2));
	List<FileVersion> fileVersions = new ArrayList<FileVersion>();
	fileVersions.add(new FileVersion(0, 123, System.currentTimeMillis(), metaChunks1));
	fileVersions.add(new FileVersion(1, 123, System.currentTimeMillis(), metaChunks2));
	MetaFileSmall metaFileSmall = new MetaFileSmall(metaFileEncryptionKeys.getPublic(), fileVersions,
			chunkEncryptionKeys);
	// encrypt the meta file
	HybridEncryptedContent encryptedMetaFile = dummyEncryption.encryptHybrid(metaFileSmall,
			metaFileEncryptionKeys.getPublic());
	encryptedMetaFile.generateVersionKey();

	// initialize put
	Parameters parameters = new Parameters().setLocationKey(metaFileSmall.getId()).setContentKey(H2HConstants.META_FILE)
			.setVersionKey(encryptedMetaFile.getVersionKey()).setProtectionKeys(protectionKeysOld)
			.setNetworkContent(encryptedMetaFile);
	// indicate to generate hash
	parameters.setHashFlag(true);
	// put encrypted meta file into network
	getter.getDataManager().putUnblocked(parameters).awaitUninterruptibly();

	// verify put
	Assert.assertNotNull(getter.getDataManager().getUnblocked(parameters).awaitUninterruptibly().data());

	// initialize a fake process context
	BasePKUpdateContext context = new TestMetaFilePKUpdateContext(protectionKeysOld, protectionKeysNew, metaFileSmall,
			parameters.getHash(), encryptedMetaFile.getVersionKey());
	// create a change protection keys process step
	ChangeProtectionKeysStep step = new ChangeProtectionKeysStep(context, getter.getDataManager());
	// run process, should not fail
	TestExecutionUtil.executeProcessTillSucceded(step);

	// verify if content protection keys have changed
	Assert.assertEquals(protectionKeysNew.getPublic(), getter.getDataManager().getUnblocked(parameters)
			.awaitUninterruptibly().data().publicKey());

	// manually trigger roll back
	step.rollback();

	// verify if content protection keys have changed to old ones
	Assert.assertEquals(protectionKeysOld.getPublic(), getter.getDataManager().getUnblocked(parameters)
			.awaitUninterruptibly().data().publicKey());
}