CipherAndAuthTag.java

  1. /**
  2.  *
  3.  * Copyright 2017 Paul Schaub, 2019-2021 Florian Schmaus
  4.  *
  5.  * Licensed under the Apache License, Version 2.0 (the "License");
  6.  * you may not use this file except in compliance with the License.
  7.  * You may obtain a copy of the License at
  8.  *
  9.  *     http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.jivesoftware.smackx.omemo.internal;

  18. import java.nio.charset.StandardCharsets;
  19. import java.security.InvalidAlgorithmParameterException;
  20. import java.security.InvalidKeyException;
  21. import java.security.NoSuchAlgorithmException;

  22. import javax.crypto.BadPaddingException;
  23. import javax.crypto.IllegalBlockSizeException;
  24. import javax.crypto.NoSuchPaddingException;

  25. /**
  26.  * Encapsulate Cipher and AuthTag.
  27.  *
  28.  * @author Paul Schaub
  29.  */
  30. public class CipherAndAuthTag {
  31.     private final byte[] key, iv, authTag;
  32.     private final boolean wasPreKey;

  33.     public CipherAndAuthTag(byte[] key, byte[] iv, byte[] authTag, boolean wasPreKey) {
  34.         this.authTag = authTag;
  35.         this.key = key;
  36.         this.iv = iv;
  37.         this.wasPreKey = wasPreKey;
  38.     }

  39.     public String decrypt(byte[] ciphertext) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException,
  40.                     NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException {
  41.         byte[] plaintext = OmemoAesCipher.decryptAesGcmNoPadding(ciphertext, key, iv);
  42.         return new String(plaintext, StandardCharsets.UTF_8);
  43.     }

  44.     public byte[] getAuthTag() {
  45.         if (authTag != null) {
  46.             return authTag.clone();
  47.         }
  48.         return null;
  49.     }

  50.     public byte[] getKey() {
  51.         if (key != null) {
  52.             return key.clone();
  53.         }
  54.         return null;
  55.     }

  56.     public byte[] getIv() {
  57.         if (iv != null) {
  58.             return iv.clone();
  59.         }
  60.         return null;
  61.     }

  62.     public boolean wasPreKeyEncrypted() {
  63.         return wasPreKey;
  64.     }
  65. }