1 /* 2 * Copyright 2018 The gRPC Authors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package io.grpc.alts.internal; 18 19 import static com.google.common.base.Preconditions.checkState; 20 21 import io.netty.buffer.ByteBuf; 22 import java.security.GeneralSecurityException; 23 import java.util.Collections; 24 import java.util.List; 25 import javax.crypto.AEADBadTagException; 26 27 public final class FakeChannelCrypter implements ChannelCrypterNetty { 28 private static final int TAG_BYTES = 16; 29 private static final byte TAG_BYTE = (byte) 0xa1; 30 31 private boolean destroyCalled = false; 32 getTagBytes()33 public static int getTagBytes() { 34 return TAG_BYTES; 35 } 36 37 @Override encrypt(ByteBuf out, List<ByteBuf> plain)38 public void encrypt(ByteBuf out, List<ByteBuf> plain) throws GeneralSecurityException { 39 checkState(!destroyCalled); 40 for (ByteBuf buf : plain) { 41 out.writeBytes(buf); 42 for (int i = 0; i < TAG_BYTES; ++i) { 43 out.writeByte(TAG_BYTE); 44 } 45 } 46 } 47 48 @Override decrypt(ByteBuf out, ByteBuf tag, List<ByteBuf> ciphertext)49 public void decrypt(ByteBuf out, ByteBuf tag, List<ByteBuf> ciphertext) 50 throws GeneralSecurityException { 51 checkState(!destroyCalled); 52 for (ByteBuf buf : ciphertext) { 53 out.writeBytes(buf); 54 } 55 while (tag.isReadable()) { 56 if (tag.readByte() != TAG_BYTE) { 57 throw new AEADBadTagException("Tag mismatch!"); 58 } 59 } 60 } 61 62 @Override decrypt(ByteBuf out, ByteBuf ciphertextAndTag)63 public void decrypt(ByteBuf out, ByteBuf ciphertextAndTag) throws GeneralSecurityException { 64 checkState(!destroyCalled); 65 ByteBuf ciphertext = ciphertextAndTag.readSlice(ciphertextAndTag.readableBytes() - TAG_BYTES); 66 decrypt(out, /*tag=*/ ciphertextAndTag, Collections.singletonList(ciphertext)); 67 } 68 69 @Override getSuffixLength()70 public int getSuffixLength() { 71 return TAG_BYTES; 72 } 73 74 @Override destroy()75 public void destroy() { 76 destroyCalled = true; 77 } 78 } 79