Debian Codegraph @

src/main/org/h2/expression/function/CryptFunction.java

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 */
6 package org.h2.expression.function;
7
8 import org.h2.engine.SessionLocal;
9 import org.h2.expression.Expression;
10 import org.h2.expression.TypedValueExpression;
11 import org.h2.message.DbException;
12 import org.h2.security.BlockCipher;
13 import org.h2.security.CipherFactory;
14 import org.h2.util.MathUtils;
15 import org.h2.util.Utils;
16 import org.h2.value.DataType;
17 import org.h2.value.TypeInfo;
18 import org.h2.value.Value;
19 import org.h2.value.ValueVarbinary;
20
21 /**
22 * An ENCRYPT or DECRYPT function.
23 */
24 public final class CryptFunction extends FunctionN {
25
26 /**
27 * ENCRYPT() (non-standard).
28 */
29 public static final int ENCRYPT = 0;
30
31 /**
32 * DECRYPT() (non-standard).
33 */
34 public static final int DECRYPT = ENCRYPT + 1;
35
36 private static final String[] NAMES = { //
37 "ENCRYPT", "DECRYPT" //
38 };
39
40 private final int function;
41
42 public CryptFunction(Expression arg1, Expression arg2, Expression arg3, int function) {
43 super(new Expression[] { arg1, arg2, arg3 });
44 this.function = function;
45 }
46
47 @Override
48 public Value getValue(SessionLocal session, Value v1, Value v2, Value v3) {
49 BlockCipher cipher = CipherFactory.getBlockCipher(v1.getString());
50 cipher.setKey(getPaddedArrayCopy(v2.getBytesNoCopy(), cipher.getKeyLength()));
51 byte[] newData = getPaddedArrayCopy(v3.getBytesNoCopy(), BlockCipher.ALIGN);
52 switch (function) {
53 case ENCRYPT:
54 cipher.encrypt(newData, 0, newData.length);
55 break;
56 case DECRYPT:
57 cipher.decrypt(newData, 0, newData.length);
58 break;
59 default:
60 throw DbException.getInternalError("function=" + function);
61 }
62 return ValueVarbinary.getNoCopy(newData);
63 }
64
65 private static byte[] getPaddedArrayCopy(byte[] data, int blockSize) {
66 return Utils.copyBytes(data, MathUtils.roundUpInt(data.length, blockSize));
67 }
68
69 @Override
70 public Expression optimize(SessionLocal session) {
71 boolean allConst = optimizeArguments(session, true);
72 TypeInfo t = args[2].getType();
73 type = DataType.isBinaryStringType(t.getValueType())
74 ? TypeInfo.getTypeInfo(Value.VARBINARY, t.getPrecision(), 0, null)
75 : TypeInfo.TYPE_VARBINARY;
76 if (allConst) {
77 return TypedValueExpression.getTypedIfNull(getValue(session), type);
78 }
79 return this;
80 }
81
82 @Override
83 public String getName() {
84 return NAMES[function];
85 }
86
87 }