001/** 002 * 003 * Copyright 2017 Paul Schaub, 2019-2021 Florian Schmaus 004 * 005 * Licensed under the Apache License, Version 2.0 (the "License"); 006 * you may not use this file except in compliance with the License. 007 * You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.jivesoftware.smackx.omemo.internal; 018 019import java.nio.charset.StandardCharsets; 020import java.security.InvalidAlgorithmParameterException; 021import java.security.InvalidKeyException; 022import java.security.NoSuchAlgorithmException; 023 024import javax.crypto.BadPaddingException; 025import javax.crypto.IllegalBlockSizeException; 026import javax.crypto.NoSuchPaddingException; 027 028/** 029 * Encapsulate Cipher and AuthTag. 030 * 031 * @author Paul Schaub 032 */ 033public class CipherAndAuthTag { 034 private final byte[] key, iv, authTag; 035 private final boolean wasPreKey; 036 037 public CipherAndAuthTag(byte[] key, byte[] iv, byte[] authTag, boolean wasPreKey) { 038 this.authTag = authTag; 039 this.key = key; 040 this.iv = iv; 041 this.wasPreKey = wasPreKey; 042 } 043 044 public String decrypt(byte[] ciphertext) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, 045 NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException { 046 byte[] plaintext = OmemoAesCipher.decryptAesGcmNoPadding(ciphertext, key, iv); 047 return new String(plaintext, StandardCharsets.UTF_8); 048 } 049 050 public byte[] getAuthTag() { 051 if (authTag != null) { 052 return authTag.clone(); 053 } 054 return null; 055 } 056 057 public byte[] getKey() { 058 if (key != null) { 059 return key.clone(); 060 } 061 return null; 062 } 063 064 public byte[] getIv() { 065 if (iv != null) { 066 return iv.clone(); 067 } 068 return null; 069 } 070 071 public boolean wasPreKeyEncrypted() { 072 return wasPreKey; 073 } 074}