最近项目想将比较重要的配置文件加密、综合考虑后决定用java jni实现,步骤如下
1.定义java本地接口
package com.msg.jni;
public class JniMsg {
static {
try {
String os = System.getProperty("os.name").toLowerCase();
String path = "F:/opt/";
System.out.println("work dir:" + path);
if (os.contains("windows")) {
System.load(path + "/ext/configlib.dll");
} else if (os.contains("linux")) {
System.load(path + "/ext/configlib.so");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public native String[] getAllCate();
}
2.生成c/c++头文件
执行 javah -jni -encoding utf-8 -classpath . com.sc.privatecloud.server.jni.JniMessage 命令生成头文件
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_msg_jni_JniMsg */
#ifndef _Included_com_msg_jni_JniMsg
#define _Included_com_msg_jni_JniMsg
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: com_msg_jni_JniMsg
* Method: getAllCate
* Signature: ()[Ljava/lang/String;
*/
JNIEXPORT jobjectArray JNICALL Java_com_msg_jni_JniMsg_getAllCate
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
3.visual studio2013编写c++代码
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include"com_msg_jni_JniMsg.h"
#define CATE_CONFIG_LENGTH 2
char *cate[482] = { "vBtqcNkMKMZ86RvvhgzNhEBdI3mu4oitNWhOFYOpndsaWivNhZNjCt83AhDR4M9wuZ3Tkxydotb+E70kLxwfcg=="
, "uME16Cvnd9zH+QYuv8dOHJVBYVQvcLVc1/GhUJjKjcV4u1jhOYKljsX9vzuE0Dna"
};
jstring CharToJobjectArray(JNIEnv* env,char **p,int len){
jclass objClass = (*env)->FindClass(env, "java/lang/String");
jobjectArray strArray = (*env)->NewObjectArray(env,
(jsize)len, objClass, 0);
jstring jstr;
int i = 0;
for (; i<len; i++)
{
jstr = (*env)->NewStringUTF(env, p[i]);
(*env)->SetObjectArrayElement(env, strArray, i, jstr);
}
return strArray;
}
JNIEXPORT jobjectArray JNICALL Java_com_sc_privatecloud_server_jni_JniMessage_getAllCate
(JNIEnv *env, jobject j){
return CharToJobjectArray(env,cate,CATE_CONFIG_LENGTH);
}
通过visual studio编译成动态链接库configlib.dll ,配置如下
4.测试
public class DemoTest {
public static void main(String args[]) {
JniMsg jnimsg=new JniMsg();
String [] config= jnimsg.getAllCate();
for(String c:config) {
System.out.println(c);
}
}
}
输出:
vBtqcNkMKMZ86RvvhgzNhEBdI3mu4oitNWhOFYOpndsaWivNhZNjCt83AhDR4M9wuZ3Tkxydotb+E70kLxwfcg==
uME16Cvnd9zH+QYuv8dOHJVBYVQvcLVc1/GhUJjKjcV4u1jhOYKljsX9vzuE0Dna
web.sendcloud.net