当前位置: 移动技术网 > 移动技术>移动开发>Android > 获取Android签名证书的公钥和私钥的简单实例

获取Android签名证书的公钥和私钥的简单实例

2019年07月24日  | 移动技术网移动技术  | 我要评论

本文以android签名jks格式的证书为例:

package com.test;

import java.io.fileinputstream;
import java.security.key;
import java.security.keystore;
import java.security.privatekey;
import java.security.publickey;

import javax.crypto.cipher;

public class signtest {

  public static void main(string[] args) {

    try {
      // 用证书的私钥解密 - 该私钥存在生成该证书的密钥库中
      fileinputstream fis2 = new fileinputstream("g:\\shanhytest.keystore");
      keystore ks = keystore.getinstance("jks"); // 加载证书库
      char[] kspwd = "shanhytest".tochararray(); // 证书库密码
      char[] keypwd = "shanhytest".tochararray(); // 证书密码
      string alias = "shanhytest";// 别名
      ks.load(fis2, kspwd); // 加载证书
      privatekey privatekey = (privatekey) ks.getkey(alias, keypwd); // 获取证书私钥
      publickey publickey = ks.getcertificate(alias).getpublickey();// 获取证书公钥
      fis2.close();

      system.out.println("privatekey = " + getkeystring(privatekey));
      system.out.println("publickey = " + getkeystring(publickey));

      // 测试加密解密字符串
      string srccontent = "今天天气不错。";

      // 将字符串使用公钥加密后,再用私钥解密后,验证是否能正常还原。
      // 因为非对称加密算法适合对小数据量的数据进行加密和解密,而且性能比较差,所以在实际的操作过程中,我们通常采用的方式是:采用非对称加密算法管理对称算法的密钥,然后用对称加密算法加密数据,这样我们就集成了两类加密算法的优点,既实现了加密速度快的优点,又实现了安全方便管理密钥的优点。
      byte[] d1 = crypt(publickey, srccontent.getbytes(), cipher.encrypt_mode);
      byte[] d2 = crypt(privatekey, d1, cipher.decrypt_mode);
      system.out.println(new string(d2));

    } catch (exception e) {
      e.printstacktrace();
    }

  }

  /**
   * 将key转换为字符串
   * 
   * @param key
   * @return
   * @author shanhy
   */
  private static string getkeystring(key key) {
    byte[] keybytes = key.getencoded();
    string s = new string(org.apache.commons.codec.binary.base64.encodebase64(keybytes));
    return s;
  }

  /**
   * 加密/解密
   * 
   * @param key
   *      私钥打包成byte[]形式
   * @param data
   *      要解密的数据
   * @param opmode
   *      操作类型(cipher.decrypt_mode为解密,cipher.encrypt_mode为加密)
   * @return 解密数据
   */
  public static byte[] crypt(key key, byte[] data, int opmode) {
    try {
      long starttime = system.currenttimemillis();
      cipher cipher = cipher.getinstance("rsa/ecb/pkcs1padding");//jdk默认标准
//     cipher cipher = cipher.getinstance("rsa/ecb/nopadding");// android默认标准
      cipher.init(opmode, key);

      byte[] result = cipher.dofinal(data);

      system.out.println((cipher.decrypt_mode==opmode?"解密":"加密") + "耗时:" + (system.currenttimemillis() - starttime));
      return result;
    } catch (exception e) {
      e.printstacktrace();
    }
    return null;

  }

}

以上这篇获取android签名证书的公钥和私钥的简单实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网