根据字符串(String)生成公钥(PublicKey)和私钥(PrivateKey)对象

1、字符串生成公钥对象 PublicKey

/**
  * 实例化公钥
  *
  * @return
  */
 private PublicKey getPubKey() {
  PublicKey publicKey = null;
  try {

   // 自己的公钥(测试)
    String pubKey ="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCVRiDkEKXy/KBTe+UmkA+feq1zGWIgBxkgbz7aBJGb5+eMKKoiDRoEHzlGndwFKm4mQWNftuMOfNcogzYpGKSEfC7sqfBPDHsGPZixMWzL3J10zkMTWo6MDIXKKqMG1Pgeq1wENfJjcYSU/enYSZkg3rFTOaBSFId+rrPjPo7Y4wIDAQAB";
      java.security.spec.X509EncodedKeySpec bobPubKeySpec = new java.security.spec.X509EncodedKeySpec(
     new BASE64Decoder().decodeBuffer(pubKey));
   // RSA对称加密算法
   java.security.KeyFactory keyFactory;
   keyFactory = java.security.KeyFactory.getInstance("RSA");
   // 取公钥匙对象
   publicKey = keyFactory.generatePublic(bobPubKeySpec);
  } catch (NoSuchAlgorithmException e) {
   e.printStackTrace();
  } catch (InvalidKeySpecException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
  return publicKey;
 }

 

 

2、字符串生成私钥对象

 /**
  * 实例化私钥
  *
  * @return
  */
 private PrivateKey getPrivateKey() {
  PrivateKey privateKey = null;
  String priKey = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAJVGIOQQpfL8oFN75SaQD596rXMZYiAHGSBvPtoEkZvn54woqiINGgQfOUad3AUqbiZBY1+24w581yiDNikYpIR8Luyp8E8MewY9mLExbMvcnXTOQxNajowMhcoqowbU+B6rXAQ18mNxhJT96dhJmSDesVM5oFIUh36us+M+jtjjAgMBAAECgYABtnxKIabF0wBD9Pf8KUsEmXPEDlaB55LyPFSMS+Ef2NlfUlgha+UQhwsxND6CEKqS5c0uG/se/2+4l0jXz+CTYBEh+USYB3gxcMKEo5XDFOGaM2Ncbc7FAKJIkYYN2DHmr4voSM5YkVibw5Lerw0kKdYyr0Xd0kmqTok3JLiLgQJBAOGZ1ao9oqWUzCKnpuTmXre8pZLmpWPhm6S1FU0vHjI0pZh/jusc8UXSRPnx1gLsgXq0ux30j968x/DmkESwxX8CQQCpY1+2p1aX2EzYO3UoTbBUTg7lCsopVNVf41xriek7XF1YyXOwEOSokp2SDQcRoKJ2PyPc2FJ/f54pigdsW0adAkAM8JTnydc9ZhZ7WmBhOrFuGnzoux/7ZaJWxSguoCg8OvbQk2hwJd3U4mWgbHWY/1XB4wHkivWBkhRpxd+6gOUjAkBH9qscS52zZzbGiwQsOk1Wk88qKdpXku4QDeUe3vmSuZwC85tNyu+KWrfM6/H74DYFbK/MzK7H8iz80uJye5jVAkAEqEB/LwlpXljFAxTID/SLZBb+bCIoV/kvg+2145F+CSSUjEWRhG/+OH0cQfqomfg36WrvHl0g/Xw06fg31HgK";
  PKCS8EncodedKeySpec priPKCS8;
  try {
   priPKCS8 = new PKCS8EncodedKeySpec(
     new BASE64Decoder().decodeBuffer(priKey));
   KeyFactory keyf = KeyFactory.getInstance("RSA");
   privateKey = keyf.generatePrivate(priPKCS8);
  } catch (IOException e) {
   e.printStackTrace();
  } catch (NoSuchAlgorithmException e) {
   e.printStackTrace();
  } catch (InvalidKeySpecException e) {
   e.printStackTrace();
  }
  return privateKey;
 }

posted @ 2012-05-29 10:34  stream1  阅读(10631)  评论(0编辑  收藏  举报