239.JNI简单使用eclipse---c层字符串加密

在c层实现字符串加密,java传递参数到c层,c层首先需要将java的字符串转化成c层的字符串,转化了以后遍历字符串的每一个字符,并进行加密(+1),c层操作的是Ascll,进行解密(-1),也是Ascll

jni/hello.c

#include 
#include 
//把java的字符串转换成c的字符串
char*   Jstring2CStr(JNIEnv*   env,   jstring   jstr)
{
	 char*   rtn   =   NULL;
	 jclass   clsstring   =   (*env)->FindClass(env,"java/lang/String");
	 jstring   strencode   =   (*env)->NewStringUTF(env,"GB2312");
	 jmethodID   mid   =   (*env)->GetMethodID(env,clsstring,   "getBytes",   "(Ljava/lang/String;)[B");
	 jbyteArray   barr=   (jbyteArray)(*env)->CallObjectMethod(env,jstr,mid,strencode); // String .getByte("GB2312");
	 jsize   alen   =   (*env)->GetArrayLength(env,barr);
	 jbyte*   ba   =   (*env)->GetByteArrayElements(env,barr,JNI_FALSE);
	 if(alen   >   0)
	 {
	  rtn   =   (char*)malloc(alen+1);         //"\0"
	  memcpy(rtn,ba,alen);
	  rtn[alen]=0;
	 }
	 (*env)->ReleaseByteArrayElements(env,barr,ba,0);  //
	 return rtn;
}


JNIEXPORT jstring JNICALL Java_com_ldw_charencode_MainActivity_encode
  (JNIEnv * env, jobject obj, jstring jstr, jint lenght){
	char* cstr = Jstring2CStr(env, jstr);
	int i;
	for(i = 0;i < lenght; i++){
		*(cstr + i) += 1;
	}
	return (*env)->NewStringUTF(env, cstr);
}

/*
 * Class:     com_itheima_charencode_MainActivity
 * Method:    decode
 * Signature: (Ljava/lang/String;)Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_com_ldw_charencode_MainActivity_decode
(JNIEnv * env, jobject obj, jstring jstr, jint lenght){
	char* cstr = Jstring2CStr(env, jstr);
		int i;
		for(i = 0;i < lenght; i++){
			*(cstr + i) -= 1;
		}
		return (*env)->NewStringUTF(env, cstr);
}

java层的代码

package com.ldw.charencode;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends Activity {

	private EditText et;
	static{
		System.loadLibrary("hello");
	}
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et = (EditText) findViewById(R.id.et);
        
    }


    public void click1(View v){
    	String text = et.getText().toString();
    	et.setText(encode(text, text.length()));
    }
    public void click2(View v){
    	String text = et.getText().toString();
    	et.setText(decode(text, text.length()));
    }
    
    public native String encode(String text, int length);
    public native String decode(String text, int length);
}

 

你可能感兴趣的:(android整理)