Hive中加密字段的UDF

2020-06-08 10:44:39 浏览数 (1)

加密函数

代码语言:javascript复制
/**
 * 自定义hive函数,用TripleDES对敏感信息加密
 *
 * @author pengjz
 */
public class UdfEncode extends GenericUDF {

    private static final String DES_KEY = "hello 1d13ef12d11a44b6aa44823e1478b529";

    @Override
    public ObjectInspector initialize(ObjectInspector[] objectInspectors) throws UDFArgumentException {
        if (objectInspectors.length != 1) {
            throw new UDFArgumentLengthException("Param must be 1 argument.");
        }
        if (objectInspectors[0].getCategory() != ObjectInspector.Category.PRIMITIVE) {
            throw new UDFArgumentTypeException(1, "A string argument was expected.");
        }
        return PrimitiveObjectInspectorFactory.javaStringObjectInspector;
    }

    @Override
    public String evaluate(DeferredObject[] deferredObjects) throws HiveException {
        if (deferredObjects[0].get() == null
                || Strings.isBlank(deferredObjects[0].get().toString())
                || "\N".equals(deferredObjects[0].get().toString())) {
            return "";
        }
        return TripleDesUtil.tripleDesEncrypt(deferredObjects[0].get().toString(), DES_KEY);
    }

    @Override
    public String getDisplayString(String[] strings) {
        return strings[0];
    }
}

解密函数

代码语言:javascript复制
/**
 * @author pengjz
 * @date 2019/10/24 19:55
 */
class UdfDecode extends GenericUDF {

    private static final String DES_KEY = "hello 1d13ef12d11a44b6aa44823e1478b529";

    @Override
    public ObjectInspector initialize(ObjectInspector[] objectInspectors) throws UDFArgumentException {
        if (objectInspectors.length != 1) {
            throw new UDFArgumentLengthException("Param must be 1 argument.");
        }
        if (objectInspectors[0].getCategory() != ObjectInspector.Category.PRIMITIVE) {
            throw new UDFArgumentTypeException(1, "A string argument was expected.");
        }
        return PrimitiveObjectInspectorFactory.javaStringObjectInspector;
    }

    @Override
    public Object evaluate(DeferredObject[] deferredObjects) throws HiveException {
        if (deferredObjects[0].get() == null
                || Strings.isBlank(deferredObjects[0].get().toString())
                || "\N".equals(deferredObjects[0].get().toString())) {
            return "";
        }
        return TripleDesUtil.tripleDesDecrypt(deferredObjects[0].get().toString(), DES_KEY);
    }

    @Override
    public String getDisplayString(String[] strings) {
        return strings[0];
    }
}

0 人点赞