android Java语言非对称加密的实现

      最近做一个android项目要用到非对称加密,下面给出代码:
package com.example.encryption;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;

import javax.crypto.Cipher;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class EntryptionActivity extends Activity {

    private static final String TAG="EntryptionActivity";
	private PrivateKey privateKey;
	private String inputString;
	private EditText encryptionEditText;

	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_entryption);
        encryptionEditText = (EditText)findViewById(R.id.encryptionedit);
        encryptionEditText.clearFocus();
        //((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE)).showSoftInput(encryptionEditText,R.id.encryptionedit);
        Button decrypitionButton = (Button)findViewById(R.id.decryptionbutton);
        Button encrypiontButton = (Button)findViewById(R.id.encryptionbutton);
        encrypiontButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				try {
					inputString = encryptionEditText.getText().toString();
					PublicEnrypt(inputString);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
        
        decrypitionButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				try {
					privateDecrypt();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
        
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_entryption, menu);
        return true;
    }
    
	/*
	 * 公钥加密
	 */
	private void PublicEnrypt(String inputString)throws Exception {
		
		Log.i(TAG, "----------------->加密");
		Cipher cipher =Cipher.getInstance("RSA");
		//实例化Key
		KeyPairGenerator keyPairGenerator=KeyPairGenerator.getInstance("RSA");
		//设置密钥长度,自己加入
		keyPairGenerator.initialize(1024);
		//获取一对钥匙
		KeyPair keyPair=keyPairGenerator.generateKeyPair();
		//获得公钥
		Key publicKey=keyPair.getPublic();
		//获得私钥 
		privateKey=keyPair.getPrivate();
		//用公钥加密
		cipher.init(Cipher.ENCRYPT_MODE, publicKey);
		byte [] result=cipher.doFinal(inputString.getBytes("UTF-8"));
		saveData(result,"public_encryt.dat");
		//将Key写入到文件
		//saveKey(privateKey,"zxx_private.key");
		//加密后的数据写入到文件
		
	}
	
	/*
	 * 私钥解密
	 */
	private void privateDecrypt() throws Exception {
		
		Cipher cipher=Cipher.getInstance("RSA");
		//得到Key
		//Key privateKey=readKey("zxx_private.key");
		//Log.i(TAG, "私钥:"+ privateKey.toString());
		//用私钥去解密
		//cipher.init(Cipher.DECRYPT_MODE, privateKey);
		cipher.init(Cipher.DECRYPT_MODE, privateKey);
		//读数据源
		byte [] src =readData("public_encryt.dat");
		Log.i(TAG, "----------------->解密");
		//得到解密后的结果
		byte[] result=cipher.doFinal(src);
		//二进制数据要变成字符串需解码
		//System.out.println(new String(result,"UTF-8"));
		String outputString = new String(result, "UTF-8");
		Log.i(TAG, outputString);
		Toast.makeText(getApplicationContext(), "您输入的明文是:" + outputString,
				Toast.LENGTH_LONG).show();
		
	}

	/**
	 * 存储加密后的数据
	 * @param result 加密数据
	 * @param fileName 存储文件名
	 * @throws Exception
	 */
	private void saveData(byte[] result, String fileName) throws Exception {
		FileOutputStream fosData = openFileOutput(fileName, MODE_PRIVATE);
		fosData.write(result);
		fosData.close();
	}
	
	public static void saveKey(Key key,String fileName)throws Exception{
		FileOutputStream fosKey=new FileOutputStream(fileName);
		ObjectOutputStream oosSecretKey =new ObjectOutputStream(fosKey);
		oosSecretKey.writeObject(key);
		oosSecretKey.close();
		fosKey.close();
	}
	
	/*//将私钥存储,可以减少内存的占用,但存储和读取降低了程序的执行效率。
	private static Key readKey(String fileName) throws Exception {
		
		FileInputStream fisKey=new FileInputStream(fileName);
		ObjectInputStream oisKey =new ObjectInputStream(fisKey);
		Key key=(Key)oisKey.readObject();
		Log.i(TAG, "私钥" + key.toString());
		oisKey.close();
		fisKey.close();
		Log.i(TAG, "-----------读取密钥");
		return key;
	}*/
	
	private  byte[] readData(String filename) throws Exception {
		FileInputStream fisDat=openFileInput(filename);
		byte [] src=new byte [fisDat.available()];
		int len =fisDat.read(src);
		int total =0;
		while(total<src.length){
			total +=len;
			len=fisDat.read(src,total,src.length-total);
		}
		fisDat.close();
		return src;
	}
    
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值