private boolean verifyMac(KeysetHandle keysetHandle, byte[] tag) { try { Mac mac = MacFactory.getPrimitive(keysetHandle); mac.verifyMac(tag, INITIAL_TEXT.getBytes()); return true; } catch (GeneralSecurityException ex) { log.error("MAC is invalid", ex); } return false; }
/** * Decrypts {@code ciphertext} with {@code aad} as additional authenticated data. The decryption * verifies the authenticity and integrity of additional data ({@code aad}), but there are no * guarantees wrt. secrecy of that data. * * <p>The ciphertext format is ciphertext || mac. The MAC is verified against (aad || ciphertext|| * t) where t is aad's length in bits represented as 64-bit bigendian unsigned integer. * * @return resulting plaintext. */ @Override public byte[] decrypt(final byte[] ciphertext, final byte[] associatedData) throws GeneralSecurityException { if (ciphertext.length < macLength) { throw new GeneralSecurityException("ciphertext too short"); } byte[] rawCiphertext = Arrays.copyOfRange(ciphertext, 0, ciphertext.length - macLength); byte[] macValue = Arrays.copyOfRange(ciphertext, ciphertext.length - macLength, ciphertext.length); byte[] aad = associatedData; if (aad == null) { aad = new byte[0]; } byte[] aadLengthInBits = Arrays.copyOf(ByteBuffer.allocate(8).putLong(8L * aad.length).array(), 8); mac.verifyMac(macValue, Bytes.concat(aad, rawCiphertext, aadLengthInBits)); return cipher.decrypt(rawCiphertext); } }
try { if (entry.getOutputPrefixType().equals(OutputPrefixType.LEGACY)) { entry.getPrimitive().verifyMac(macNoPrefix, Bytes.concat(data, formatVersion)); } else { entry.getPrimitive().verifyMac(macNoPrefix, data); for (PrimitiveSet.Entry<Mac> entry : entries) { try { entry.getPrimitive().verifyMac(mac, data);