将PrivateKey保存到本地

在做文件加密时,需要将私钥保存到本地,我在使用writeNewObject是老是报错,说是没有序列化

网上百度了一下,发现在Java中要保存对象的话,必须是序列化,但是找了一下PrivateKey好像已经是序列化了,但是就是不行,

没办法只好采取存二进制数据流的办法了

以下是解决的代码

filename是我自己的参数,不用管它。

/**
	 * 读privatekey对象
	 */
	public PrivateKey getPrivateKey(String filename) {
		PrivateKey privateKey=null;
		SharedPreferences preferences = context.getSharedPreferences("base64",Context.MODE_PRIVATE);
		String privateKeyBase64 = preferences.getString(filename, "");
		//Log.d("get",filename+" ; "+privateKeyBase64 );
		if (privateKeyBase64 == "") {
			return null;
		}
		//读取字节
		byte[] base64 = Base64.decodeBase64(privateKeyBase64.getBytes());
		KeyFactory keyFactory;
		try {
			keyFactory = KeyFactory.getInstance("RSA");
			PKCS8EncodedKeySpec pKCS8EncodedKeySpec =new PKCS8EncodedKeySpec(base64);
			privateKey = keyFactory.generatePrivate(pKCS8EncodedKeySpec);
			//Log.d("get",filename+" ; "+privateKey.toString() );
		} catch (InvalidKeySpecException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} // 指定算法RSA,得到一个KeyFactory的实例
		
			
		return privateKey;
	}
	/**
	 * 设置privatekey对象
	 */
	public void savePrivateKey(String filename,PrivateKey privateKey) {
		SharedPreferences preferences = context.getSharedPreferences("base64",Context.MODE_PRIVATE);
		//将字节流编码成base64的字符窜
		String privateKeyBase64 = new String(Base64.encodeBase64(privateKey.getEncoded()));
		Editor editor = preferences.edit();
		editor.putString(filename, privateKeyBase64);
		editor.commit();

	}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值