Hive UDF实现RAS加密解密

话不多说,直接上代码

RSA加密:

import org.apache.commons.codec.binary.Base64;
import org.apache.hadoop.hive.ql.exec.MapredContext;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDF;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * CREATE FUNCTION default.rsa_encoder AS 'com.howe.hive.udf.encoder.RsaEncoder' USING JAR 'hdfs://nameservice1/user/howe/MyHiveUdf.jar';
 * select rsa_encoder('测试123');
 * 
 * CREATE temporary function rsa_decoder as 'com.howe.hive.udf.encoder.RsaDecoder';
 */
public class RsaEncoder extends GenericUDF {

    private static final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    //非对称密钥算法
    public static final String KEY_ALGORITHM = "RSA";

    // RSA 私钥
    private static String RasPublicKey =
            "RSA Public Key";

    private Cipher cipher = null;

    @Override
    public void configure(MapredContext context) {
        System.out.println(new Date() + "######## configure");

        if(null != context) {
            //从jobConf中获取私钥
            String confPublicKey = context.getJobConf().get("com.szlanyou.udf.ras.publickey");

            if( confPublicKey != null && confPublicKey.length() > 0 ) {
                RasPublicKey = confPublicKey;
            }
        }
    }

    @Override
    public ObjectInspector initialize(ObjectInspector[] arguments) {

        //System.out.println(formatter.format(new Date()) + "######## initialize");

        try {
            //实例化密钥工厂
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            //初始化公钥
            //密钥材料转换
            X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.decodeBase64(RasPublicKey));
            //产生公钥
            PublicKey pubKey = keyFactory.generatePublic(x509KeySpec);

            //数据加密
            cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, pubKey);

            System.out.println(formatter.format(new Date()) + "######## The Initialization Of Cipher Has Completed Successfully");

        } catch (Exception e) {
            e.printStackTrace();
            cipher = null;
            System.out.println(formatter.format(new Date()) + "######## Error: Initialization Failed!");
        }

        return PrimitiveObjectInspectorFactory.getPrimitiveJavaObjectInspector(PrimitiveObjectInspector.PrimitiveCategory.STRING);
    }

    @Override
    public Object evaluate(DeferredObject[] args) throws HiveException {

        if( cipher == null ) return null;
        try {
            final String text = args[0].get().toString();

            if ( text != null && text.length() > 0)
                return Base64.encodeBase64String(cipher.doFinal(text.getBytes()));
            else
                return null;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public String getDisplayString(String[] strings) {
        return "Usage: FUNC_(String encrypted_text)";
    }
}

RSA解密:

import org.apache.commons.codec.binary.Base64;
import org.apache.hadoop.hive.ql.exec.MapredContext;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDF;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 
 * CREATE FUNCTION default.rsa_decoder AS 'com.howe.hive.udf.encoder.RsaDecoder' USING JAR 'hdfs://nameservice1/usr/wuhhao/MyHiveUdf.jar';
 * select rsa_decoder('OOcPjdG1quiKxbZkzwlm95CLKoa553rjSg8E6ZcDvEQ/xZzIRuA9ivAMyuN3FJv1LIg1/T071j3iYBFc+TfLKw==');
 * select rsa_decoder(rsa_encoder('Howe'));
 * 
 * add jar /root/howe/MyHiveUdf.jar;
 * CREATE temporary function rsa_decoder as 'com.howe.hive.udf.encoder.RsaDecoder';
 */
public class RsaDecoder extends GenericUDF {

    private static final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    //非对称密钥算法
    public static final String KEY_ALGORITHM = "RSA";

    // RSA 私钥
    private static String RasPrivateKey = "RAS Private Key";

    private Cipher cipher = null;

    @Override
    public void configure(MapredContext context) {
        System.out.println(new Date() + "######## configure");

        if(null != context) {
            //从jobConf中获取私钥
            String confPrivateKey = context.getJobConf().get("com.howe.udf.ras.privatekey");

            if( confPrivateKey != null && confPrivateKey.length() > 0 ) {
                RasPrivateKey = confPrivateKey;
            }
        }
    }

    @Override
    public ObjectInspector initialize(ObjectInspector[] arguments) {

        //System.out.println(formatter.format(new Date()) + "######## initialize");

        try {
            //取得私钥
            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(RasPrivateKey));
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            //生成私钥
            PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
            //数据解密
            cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, privateKey);

            System.out.println(formatter.format(new Date()) + "######## The Initialization Of Cipher Has Completed Successfully");

        } catch (Exception e) {
            e.printStackTrace();
            cipher = null;
            System.out.println(formatter.format(new Date()) + "######## Error: Initialization Failed!");
        }

        return PrimitiveObjectInspectorFactory.getPrimitiveJavaObjectInspector(PrimitiveObjectInspector.PrimitiveCategory.STRING);
    }

    @Override
    public Object evaluate(DeferredObject[] args) throws HiveException {
        if( cipher == null ) return null;

        try {

            final String text = args[0].get().toString();
            if ( text != null && text.length() > 0)
                return new String(cipher.doFinal(Base64.decodeBase64(text)));
            else
                return null;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public String getDisplayString(String[] strings) {
        return "Usage: FUNC_(String encrypted_text)";
    }
}

附RAS生成公钥私钥的代码(网上找的,找不到来源了,侵权删)

import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.codec.binary.Base64;

/**
 * 非对称加密算法RSA算法组件
 * 非对称算法一般是用来传送对称加密算法的密钥来使用的,相对于DH算法,RSA算法只需要一方构造密钥,不需要
 * 大费周章的构造各自本地的密钥对了。DH算法只能算法非对称算法的底层实现。而RSA算法算法实现起来较为简单
 *
 * @author kongqz
 */
public class RsaCoder2 {

    //非对称密钥算法
    public static final String KEY_ALGORITHM = "RSA";


    /**
     * 密钥长度,DH算法的默认密钥长度是1024
     * 密钥长度必须是64的倍数,在512到65536位之间
     */
    private static final int KEY_SIZE = 512;
    //公钥
    private static final String PUBLIC_KEY = "RSAPublicKey";

    //私钥
    private static final String PRIVATE_KEY = "RSAPrivateKey";

    /**
     * 初始化密钥对
     *
     * @return Map 甲方密钥的Map
     */
    public static Map initKey() throws Exception {
        //实例化密钥生成器
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        //初始化密钥生成器
        keyPairGenerator.initialize(KEY_SIZE);
        //生成密钥对
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        //甲方公钥
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        //甲方私钥
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        //将密钥存储在map中
        Map keyMap = new HashMap();
        keyMap.put(PUBLIC_KEY, publicKey);
        keyMap.put(PRIVATE_KEY, privateKey);
        return keyMap;

    }


    /**
     * 私钥加密
     *
     * @param data 待加密数据
     * @param key       密钥
     * @return byte[] 加密数据
     */
    public static byte[] encryptByPrivateKey(byte[] data, byte[] key) throws Exception {

        //取得私钥
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        //生成私钥
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
        //数据加密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);
        return cipher.doFinal(data);
    }

    /**
     * 公钥加密
     *
     * @param data 待加密数据
     * @param key       密钥
     * @return byte[] 加密数据
     */
    public static byte[] encryptByPublicKey(byte[] data, byte[] key) throws Exception {

        //实例化密钥工厂
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        //初始化公钥
        //密钥材料转换
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);
        //产生公钥
        PublicKey pubKey = keyFactory.generatePublic(x509KeySpec);

        //数据加密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        return cipher.doFinal(data);
    }

    /**
     * 私钥解密
     *
     * @param data 待解密数据
     * @param key  密钥
     * @return byte[] 解密数据
     */
    public static byte[] decryptByPrivateKey(byte[] data, byte[] key) throws Exception {
        //取得私钥
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        //生成私钥
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
        //数据解密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        return cipher.doFinal(data);
    }

    /**
     * 公钥解密
     *
     * @param data 待解密数据
     * @param key  密钥
     * @return byte[] 解密数据
     */
    public static byte[] decryptByPublicKey(byte[] data, byte[] key) throws Exception {

        //实例化密钥工厂
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        //初始化公钥
        //密钥材料转换
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);
        //产生公钥
        PublicKey pubKey = keyFactory.generatePublic(x509KeySpec);
        //数据解密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, pubKey);
        return cipher.doFinal(data);
    }

    /**
     * 取得私钥
     *
     * @param keyMap 密钥map
     * @return byte[] 私钥
     */
    public static byte[] getPrivateKey(Map keyMap) {
        Key key = (Key) keyMap.get(PRIVATE_KEY);
        return key.getEncoded();
    }

    /**
     * 取得公钥
     *
     * @param keyMap 密钥map
     * @return byte[] 公钥
     */
    public static byte[] getPublicKey(Map keyMap) throws Exception {
        Key key = (Key) keyMap.get(PUBLIC_KEY);
        return key.getEncoded();
    }

    /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        //初始化密钥
        //生成密钥对
        Map keyMap = RsaCoder2.initKey();

        //公钥
        byte[] publicKey = RsaCoder2.getPublicKey(keyMap);

        //私钥
        byte[] privateKey = RsaCoder2.getPrivateKey(keyMap);
        System.out.println("公钥:\n" + Base64.encodeBase64String(publicKey));
        System.out.println("私钥:\n" + Base64.encodeBase64String(privateKey));

        String str = "441881199503020202";
        System.out.println("================密钥对构造完毕,甲方将公钥公布给乙方,开始进行加密数据的传输=============");
        System.out.println("\n===========甲方向乙方发送加密数据==============");
        System.out.println("原文:" + str);
        //甲方进行数据的加密
        byte[] code1 = RsaCoder2.encryptByPrivateKey(str.getBytes(), privateKey);
        System.out.println("加密后的数据:" + Base64.encodeBase64String(code1));
        System.out.println("===========乙方使用甲方提供的公钥对数据进行解密==============");
        //乙方进行数据的解密
        byte[] decode1 = RsaCoder2.decryptByPublicKey(code1, publicKey);
        System.out.println("乙方解密后的数据:" + new String(decode1) + "\n\n");

        System.out.println("===========反向进行操作,乙方向甲方发送数据==============\n\n");

        str = "441881199503020202";

        System.out.println("原文:" + str);

        //乙方使用公钥对数据进行加密
        byte[] code2 = RsaCoder2.encryptByPublicKey(str.getBytes(), publicKey);
        System.out.println("===========乙方使用公钥对数据进行加密==============");
        System.out.println("加密后的数据:" + Base64.encodeBase64String(code2));

        System.out.println("=============乙方将数据传送给甲方======================");
        System.out.println("===========甲方使用私钥对数据进行解密==============");

        //甲方使用私钥对数据进行解密
        byte[] decode2 = RsaCoder2.decryptByPrivateKey(code2, privateKey);

        System.out.println("甲方解密后的数据:" + new String(decode2));
    }
}

你可能感兴趣的:(hive,hadoop,big,data)