您的位置:首页 > 编程语言 > Java开发

jdk1.4 使用RSA加解密

2016-04-22 16:10 330 查看
需要加  Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

package com.paic.ebank.creditcard.common.util;

import java.security.KeyFactory;

import java.security.MessageDigest;

import java.security.PrivateKey;

import java.security.PublicKey;

import java.security.Security;

import java.security.Signature;

import java.security.KeyPair;

import java.security.KeyPairGenerator;

import java.security.SecureRandom;

import java.security.spec.PKCS8EncodedKeySpec;

import java.security.spec.X509EncodedKeySpec;

import java.util.Arrays;

import java.util.Date;

import javax.crypto.Cipher;

import org.apache.commons.codec.binary.Base64;

/**

* <p>

* 封装同RSA非对称加密算法有关的方法,可用于数字签名,RSA加密解密

* </p>

*

* @Copyright:WDSsoft

*/

public class RSATool {

public RSATool() {

 

}

/**使用私钥加密数据

  * 用一个已打包成byte[]形式的私钥加密数据,即数字签名

  *

  * @param keyInByte

  *            打包成byte[]的私钥

  * @param source

  *            要签名的数据,一般应是数字摘要

  * @return 签名 byte[]

  */

public static byte[] sign(byte[] keyInByte, byte[] source) {

  try {

   PKCS8EncodedKeySpec priv_spec = new PKCS8EncodedKeySpec(keyInByte);

   KeyFactory mykeyFactory = KeyFactory.getInstance("RSA");

   PrivateKey privKey = mykeyFactory.generatePrivate(priv_spec);

   Signature sig = Signature.getInstance("SHA1withRSA");

   sig.initSign(privKey);

   sig.update(source);

   return sig.sign();

  } catch (Exception e) {

   return null;

  }

}

/**

  * 验证数字签名

  *

  * @param keyInByte

  *            打包成byte[]形式的公钥

  * @param source

  *            原文的数字摘要

  * @param sign

  *            签名(对原文的数字摘要的签名)

  * @return 是否证实 boolean

  */

public static boolean verify(byte[] keyInByte, byte[] source, byte[] sign) {

  try {

   KeyFactory mykeyFactory = KeyFactory.getInstance("RSA");

   Signature sig = Signature.getInstance("SHA1withRSA");

   X509EncodedKeySpec pub_spec = new X509EncodedKeySpec(keyInByte);

   PublicKey pubKey = mykeyFactory.generatePublic(pub_spec);

   sig.initVerify(pubKey);

   sig.update(source);

   return sig.verify(sign);

  } catch (Exception e) {

   return false;

  }

}

/**

  * 建立新的密钥对,返回打包的byte[]形式私钥和公钥

  *

  * @return 包含打包成byte[]形式的私钥和公钥的object[],其中,object[0]为私钥byte[],object[1]为公钥byte[]

  */

public static Object[] giveRSAKeyPairInByte() {

  KeyPair newKeyPair = creatmyKey();

  if (newKeyPair == null)

   return null;

  Object[] re = new Object[2];

  if (newKeyPair != null) {

   PrivateKey priv = newKeyPair.getPrivate();

   byte[] b_priv = priv.getEncoded();

   PublicKey pub = newKeyPair.getPublic();

   byte[] b_pub = pub.getEncoded();

   re[0] = b_priv;

   re[1] = b_pub;

   return re;

  }

  return null;

}

/**

  * 新建密钥对

  *

  * @return KeyPair对象

  */

public static KeyPair creatmyKey() {

  KeyPair myPair;

  long mySeed;

  mySeed = System.currentTimeMillis();

  try {

   KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");

   SecureRandom secureRandom = new SecureRandom(new Date().toString().getBytes());

   keyGen.initialize(1024, secureRandom);

   myPair = keyGen.generateKeyPair();

  } catch (Exception e1) {

   return null;

  }

  return myPair;

}

/**

  * 使用RSA公钥加密数据

  *

  * @param pubKeyInByte

  *            打包的byte[]形式公钥

  * @param data

  *            要加密的数据

  * @return 加密数据

  */

public static byte[] encryptToPublicByRSA(byte[] pubKeyInByte, byte[] data) {

  try {

   Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

   KeyFactory mykeyFactory = KeyFactory.getInstance("RSA");

   X509EncodedKeySpec pub_spec = new X509EncodedKeySpec(pubKeyInByte);

   PublicKey pubKey = mykeyFactory.generatePublic(pub_spec);

   Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");

   cipher.init(Cipher.ENCRYPT_MODE, pubKey);

   return cipher.doFinal(data);

  } catch (Exception e) {

   return null;

  }

}

/**

  * 用RSA私钥解密

  *

  * @param privKeyInByte

  *            私钥打包成byte[]形式

  * @param data

  *            要解密的数据

  * @return 解密数据

  */

public static byte[] decryptToPrivateByRSA(byte[] privKeyInByte, byte[] data) {

  try {

  Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

  PKCS8EncodedKeySpec priv_spec = new PKCS8EncodedKeySpec(privKeyInByte);

   KeyFactory mykeyFactory = KeyFactory.getInstance("RSA");

   PrivateKey privKey = mykeyFactory.generatePrivate(priv_spec);

   Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");

   cipher.init(Cipher.DECRYPT_MODE, privKey);

   return cipher.doFinal(data);

  } catch (Exception e) {

   return null;

  }

}

 

/**

 * 使用RSA私钥加密数据

 *

 * @param pubKeyInByte

 *            打包的byte[]形式私钥

 * @param data

 *            要加密的数据

 * @return 加密数据

 */

public static byte[] encryptToPrivateByRSA(byte[] privKeyInByte, byte[] data) {

  try {

   Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    PKCS8EncodedKeySpec priv_spec = new PKCS8EncodedKeySpec(

      privKeyInByte);

    KeyFactory mykeyFactory = KeyFactory.getInstance("RSA");

    PrivateKey privKey = mykeyFactory.generatePrivate(priv_spec);

    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");

    cipher.init(Cipher.ENCRYPT_MODE, privKey);

    return cipher.doFinal(data);

   } catch (Exception e) {

    return null;

   }

}

/**

 * 用RSA公钥解密

 *

 * @param privKeyInByte

 *            公钥打包成byte[]形式

 * @param data

 *            要解密的数据

 * @return 解密数据

 * @throws Exception

 */

public static byte[] decryptToPublicByRSA(byte[] pubKeyInByte, byte[] data) {

 try {

   Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

   KeyFactory mykeyFactory = KeyFactory.getInstance("RSA");

   X509EncodedKeySpec pub_spec = new X509EncodedKeySpec(pubKeyInByte);

   PublicKey pubKey = mykeyFactory.generatePublic(pub_spec);

   Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");

   cipher.init(Cipher.DECRYPT_MODE, pubKey);

   return cipher.doFinal(data);

  } catch (Exception e) {

   return null;

  }

}

/**

 * 计算字符串的SHA数字摘要,以byte[]形式返回

 */

public static byte[] MdigestSHA(String source) {

 //byte[] nullreturn = { 0 };

 try {

  MessageDigest thisMD = MessageDigest.getInstance("SHA");

  byte[] digest = thisMD.digest(source.getBytes("UTF-8"));

  return digest;

 } catch (Exception e) {

  return null;

 }

}

 /**

   *测试

   * 

   */

 public static void main(String[] args) {

   try {

    //私钥加密 公钥解密

    //生成私钥-公钥对

    Object[] v = giveRSAKeyPairInByte();

    //获得摘要

    byte[] source =MdigestSHA("假设这是要加密的客户数据");

    //使用私钥对摘要进行加密 获得密文 即数字签名

    byte[] sign = sign((byte[]) v[0], source);

    //使用公钥对密文进行解密,解密后与摘要进行匹配

    boolean yes = verify((byte[]) v[1], source, sign);

    if (yes)

     System.out.println("匹配成功 合法的签名!");

   

   //公钥加密私钥解密

    //获得摘要

    byte[] sourcepub_pri = ("13265986584||316494646546486498||01||public").getBytes("UTF-8");

    //使用公钥对摘要进行加密 获得密文

    byte[] signpub_pri =encryptToPublicByRSA((byte[]) v[1] ,sourcepub_pri);

    //System.out.println("公钥加密密文:"+new String(Base64.encodeBase64(signpub_pri)));

    //使用私钥对密文进行解密 返回解密后的数据

    byte[] newSourcepub_pri=decryptToPrivateByRSA((byte[]) v[0],signpub_pri);

    System.out.println("私钥解密:"+new String(newSourcepub_pri,"UTF-8"));

    //对比源数据与解密后的数据

    if(Arrays.equals(sourcepub_pri, newSourcepub_pri))

     System.out.println("匹配成功 合法的私钥!");

   

   

    //私钥加密公钥解密

    //获得摘要

    //byte[] sourcepri_pub = MdigestSHA("假设这是要加密的客户数据");

    byte[] sourcepri_pub = ("13265986584||316494646546486498||01||private").getBytes();

    //使用私钥对摘要进行加密 获得密文

    byte[] signpri_pub =encryptToPrivateByRSA((byte[]) v[0] ,sourcepri_pub);

   

 //   System.out.println("私钥加密密文:"+new String(Base64.encodeBase64(signpri_pub)));

    //使用公钥对密文进行解密 返回解密后的数据

    byte[] newSourcepri_pub=decryptToPublicByRSA((byte[]) v[1],signpri_pub);

    System.out.println("公钥解密:"+new String(newSourcepri_pub));   

   } catch (Exception e) {

    e.printStackTrace();

   }

  

 

 }

}

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: