Skip to content

Instantly share code, notes, and snippets.

@TroniPM
Last active December 6, 2017 20:15
Show Gist options
  • Save TroniPM/6c93c3f6b1dd2c242d00022edda9b1d5 to your computer and use it in GitHub Desktop.
Save TroniPM/6c93c3f6b1dd2c242d00022edda9b1d5 to your computer and use it in GitHub Desktop.
Autentication symmetric
public byte[] autenticacao(byte[] input, SecretKey secret) throws DataLengthException, InvalidCipherTextException {
CBCBlockCipher cbcBlockCipher = new CBCBlockCipher(new AESEngine());
//SecureRandom random = new SecureRandom();
BlockCipherPadding bcp = new PKCS7Padding();
PaddedBufferedBlockCipher pbbc = new PaddedBufferedBlockCipher(cbcBlockCipher, bcp);
int blockSize = cbcBlockCipher.getBlockSize();
int inputOffset = 0;
int inputLength = input.length;
int outputOffset = 0;
byte[] iv = new byte[blockSize];
outputOffset += blockSize;
pbbc.init(true, new ParametersWithIV(new KeyParameter(secret.getEncoded()), iv));
byte[] output = new byte[pbbc.getOutputSize(inputLength) + outputOffset];
System.arraycopy(iv, 0, output, 0, blockSize);
int outputLength = outputOffset + pbbc.processBytes(input, inputOffset, inputLength, output, outputOffset);
outputLength += pbbc.doFinal(output, outputLength);
//Pego apenas o último bloco
byte[] out = new byte[blockSize];
System.arraycopy(output, outputLength - blockSize, out, 0, blockSize);
return out;
}
private byte[] process(byte[] input, boolean encrypt, SecretKey secret) throws DataLengthException, IllegalStateException, InvalidCipherTextException {
CBCBlockCipher cbcBlockCipher = new CBCBlockCipher(new AESEngine());
BlockCipherPadding bcp = new PKCS7Padding();
PaddedBufferedBlockCipher pbbc = new PaddedBufferedBlockCipher(cbcBlockCipher, bcp);
int blockSize = cbcBlockCipher.getBlockSize();
int inputOffset = 0;
int inputLength = input.length;
int outputOffset = 0;
byte[] iv = new byte[blockSize];
if (encrypt) {
//random.nextBytes(iv);
outputOffset += blockSize;
} else {
System.arraycopy(input, 0, iv, 0, blockSize);
inputOffset += blockSize;
inputLength -= blockSize;
}
pbbc.init(encrypt, new ParametersWithIV(new KeyParameter(secret.getEncoded()), iv));
byte[] output = new byte[pbbc.getOutputSize(inputLength) + outputOffset];
if (encrypt) {
System.arraycopy(iv, 0, output, 0, blockSize);
}
int outputLength = outputOffset + pbbc.processBytes(input, inputOffset, inputLength, output, outputOffset);
outputLength += pbbc.doFinal(output, outputLength);
byte[] out = new byte[outputLength];
System.arraycopy(output, 0, out, 0, outputLength);
return out;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment