话不多说,直接上代码
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[] arg