001/* 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, software 013 * distributed under the License is distributed on an "AS IS" BASIS, 014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 015 * See the License for the specific language governing permissions and 016 * limitations under the License. 017 */ 018package org.apache.hadoop.hbase.io.crypto.aes; 019 020import java.io.InputStream; 021import java.security.InvalidAlgorithmParameterException; 022import java.security.InvalidKeyException; 023import java.security.Key; 024import javax.crypto.spec.IvParameterSpec; 025 026import org.apache.hadoop.hbase.io.crypto.Decryptor; 027import org.apache.yetus.audience.InterfaceAudience; 028import org.apache.yetus.audience.InterfaceStability; 029 030import org.apache.hbase.thirdparty.com.google.common.base.Preconditions; 031 032@InterfaceAudience.Private 033@InterfaceStability.Evolving 034public class AESDecryptor implements Decryptor { 035 036 private javax.crypto.Cipher cipher; 037 private Key key; 038 private byte[] iv; 039 private boolean initialized = false; 040 041 public AESDecryptor(javax.crypto.Cipher cipher) { 042 this.cipher = cipher; 043 } 044 045 javax.crypto.Cipher getCipher() { 046 return cipher; 047 } 048 049 @Override 050 public void setKey(Key key) { 051 Preconditions.checkNotNull(key, "Key cannot be null"); 052 this.key = key; 053 } 054 055 @Override 056 public int getIvLength() { 057 return AES.IV_LENGTH; 058 } 059 060 @Override 061 public int getBlockSize() { 062 return AES.BLOCK_SIZE; 063 } 064 065 @Override 066 public void setIv(byte[] iv) { 067 Preconditions.checkNotNull(iv, "IV cannot be null"); 068 Preconditions.checkArgument(iv.length == AES.IV_LENGTH, "Invalid IV length"); 069 this.iv = iv; 070 } 071 072 @Override 073 public InputStream createDecryptionStream(InputStream in) { 074 if (!initialized) { 075 init(); 076 } 077 return new javax.crypto.CipherInputStream(in, cipher); 078 } 079 080 @Override 081 public void reset() { 082 init(); 083 } 084 085 protected void init() { 086 try { 087 if (iv == null) { 088 throw new NullPointerException("IV is null"); 089 } 090 cipher.init(javax.crypto.Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv)); 091 } catch (InvalidKeyException e) { 092 throw new RuntimeException(e); 093 } catch (InvalidAlgorithmParameterException e) { 094 throw new RuntimeException(e); 095 } 096 initialized = true; 097 } 098 099}