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; 025import org.apache.hadoop.hbase.io.crypto.Decryptor; 026import org.apache.yetus.audience.InterfaceAudience; 027import org.apache.yetus.audience.InterfaceStability; 028 029import org.apache.hbase.thirdparty.com.google.common.base.Preconditions; 030 031@InterfaceAudience.Private 032@InterfaceStability.Evolving 033public class AESDecryptor implements Decryptor { 034 035 private javax.crypto.Cipher cipher; 036 private Key key; 037 private byte[] iv; 038 private boolean initialized = false; 039 040 public AESDecryptor(javax.crypto.Cipher cipher) { 041 this.cipher = cipher; 042 } 043 044 javax.crypto.Cipher getCipher() { 045 return cipher; 046 } 047 048 @Override 049 public void setKey(Key key) { 050 Preconditions.checkNotNull(key, "Key cannot be null"); 051 this.key = key; 052 } 053 054 @Override 055 public int getIvLength() { 056 return AES.IV_LENGTH; 057 } 058 059 @Override 060 public int getBlockSize() { 061 return AES.BLOCK_SIZE; 062 } 063 064 @Override 065 public void setIv(byte[] iv) { 066 Preconditions.checkNotNull(iv, "IV cannot be null"); 067 Preconditions.checkArgument(iv.length == AES.IV_LENGTH, "Invalid IV length"); 068 this.iv = iv; 069 } 070 071 @Override 072 public InputStream createDecryptionStream(InputStream in) { 073 if (!initialized) { 074 init(); 075 } 076 return new javax.crypto.CipherInputStream(in, cipher); 077 } 078 079 @Override 080 public void reset() { 081 init(); 082 } 083 084 protected void init() { 085 try { 086 if (iv == null) { 087 throw new NullPointerException("IV is null"); 088 } 089 cipher.init(javax.crypto.Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv)); 090 } catch (InvalidKeyException e) { 091 throw new RuntimeException(e); 092 } catch (InvalidAlgorithmParameterException e) { 093 throw new RuntimeException(e); 094 } 095 initialized = true; 096 } 097 098}