· 8 years ago · Dec 09, 2017, 11:52 AM
1public byte[] autenticacao(byte[] input, SecretKey secret) throws DataLengthException, InvalidCipherTextException {
2 CBCBlockCipher cbcBlockCipher = new CBCBlockCipher(new AESEngine());
3 //SecureRandom random = new SecureRandom();
4 BlockCipherPadding bcp = new PKCS7Padding();
5 PaddedBufferedBlockCipher pbbc = new PaddedBufferedBlockCipher(cbcBlockCipher, bcp);
6
7 int blockSize = cbcBlockCipher.getBlockSize();
8 int inputOffset = 0;
9 int inputLength = input.length;
10 int outputOffset = 0;
11
12 byte[] iv = new byte[blockSize];
13 outputOffset += blockSize;
14
15 pbbc.init(true, new ParametersWithIV(new KeyParameter(secret.getEncoded()), iv));
16 byte[] output = new byte[pbbc.getOutputSize(inputLength) + outputOffset];
17
18 System.arraycopy(iv, 0, output, 0, blockSize);
19
20 int outputLength = outputOffset + pbbc.processBytes(input, inputOffset, inputLength, output, outputOffset);
21
22 outputLength += pbbc.doFinal(output, outputLength);
23
24 //Pego apenas o último bloco
25 byte[] out = new byte[blockSize];
26 System.arraycopy(output, outputLength - blockSize, out, 0, blockSize);
27
28 return out;
29}
30
31private byte[] process(byte[] input, boolean encrypt, SecretKey secret) throws DataLengthException, IllegalStateException, InvalidCipherTextException {
32 CBCBlockCipher cbcBlockCipher = new CBCBlockCipher(new AESEngine());
33 BlockCipherPadding bcp = new PKCS7Padding();
34 PaddedBufferedBlockCipher pbbc = new PaddedBufferedBlockCipher(cbcBlockCipher, bcp);
35
36 int blockSize = cbcBlockCipher.getBlockSize();
37 int inputOffset = 0;
38 int inputLength = input.length;
39 int outputOffset = 0;
40
41 byte[] iv = new byte[blockSize];
42 if (encrypt) {
43 //random.nextBytes(iv);
44 outputOffset += blockSize;
45 } else {
46 System.arraycopy(input, 0, iv, 0, blockSize);
47 inputOffset += blockSize;
48 inputLength -= blockSize;
49 }
50
51 pbbc.init(encrypt, new ParametersWithIV(new KeyParameter(secret.getEncoded()), iv));
52 byte[] output = new byte[pbbc.getOutputSize(inputLength) + outputOffset];
53
54 if (encrypt) {
55 System.arraycopy(iv, 0, output, 0, blockSize);
56 }
57
58 int outputLength = outputOffset + pbbc.processBytes(input, inputOffset, inputLength, output, outputOffset);
59
60 outputLength += pbbc.doFinal(output, outputLength);
61
62 byte[] out = new byte[outputLength];
63 System.arraycopy(output, 0, out, 0, outputLength);
64
65 return out;
66}