java 实现RSA实现数据的私钥加密以及公钥解密

原创 2015年11月21日 10:32:17

1.第一个类KeyGenerate.java生成RSA公钥与私钥并保存到文件中

package signature;


import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;


import org.junit.Test;


import sun.misc.BASE64Encoder;


/**
 * @author numb-tangsi
 */
public class KeyGenerate {


    public static final String PUBLIC_KEY_FILE_PATH = "d:/publickey.keystore";
    
    public static final String PRIVATE_KEY_FILE_PATH = "d:/privatekey.keystore";
    

@Test
public void test1() throws NoSuchAlgorithmException, IOException {
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
SecureRandom random = new SecureRandom();
generator.initialize(1024, random);
KeyPair keyPair = generator.generateKeyPair();
PrivateKey privateKey =  keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();
//将生成的私钥及公钥base64编码
String privateKeyStr = new BASE64Encoder().encode(privateKey.getEncoded());
String publicKeyStr = new BASE64Encoder().encode(publicKey.getEncoded());

System.out.println("privateKeyStr = " + privateKeyStr);
System.out.println("publicKeyStr = " + publicKeyStr);

//将公钥以及私钥写入文件保存
File privateFile = new File(PRIVATE_KEY_FILE_PATH);
writeStr2File(privateFile, privateKeyStr);

File publicFile = new File(PUBLIC_KEY_FILE_PATH);
writeStr2File(publicFile, publicKeyStr);

}

public  static void writeStr2File(File file, String content) throws IOException
{
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write(content);
writer.flush();
writer.close();
}


}



2.第二个类 SignatureData.java将元数据用私钥生成签名

package signature;


import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;


import org.junit.Test;


import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;


/**
 * @author numb-tangsi
 */
public class SignatureData {


/**
* 私钥加密
* @throws IOException
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
* @throws InvalidKeyException
* @throws SignatureException
*/
@Test
public void test1() throws IOException, NoSuchAlgorithmException,
InvalidKeySpecException, InvalidKeyException, SignatureException {


//base64后的私钥串,这个串实际上应该从上一步的私钥文件privatekey.keystore中读取
String privateKeyStr = "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAKmtw5lgEY0BRYEs9VNuoXIDjRo/"
+ "T5TqWrNJY7tIiObVtgS0+dTx2kaZIL2TuOe+naDSyzlVlqYlzOx0UpID9sD3Pmr8NR5y0Xxu+IDM"
+ "Yo0HO0H2Xl7E9FLyOUCL0uurLgNx14Fl9iDBu4JWY42h0eEuYVsGuOye3YOBdMlaCKuDAgMBAAEC"
+ "gYEAmXdTYUaVuS38OlB6dwKpvOBfX+0BQpQQgvYO4RZC1F1Y6rrw99vja1UWWsDgTaKHGS1up6W0"
+ "wwOPbBHtmKlDJF20DZdvWSGLcyuhX779W1s+NMFC9fn1KP6MAqEYfYcY5rClQX2Zi+/NvrvUjIqq"
+ "MyQjZncs+FW8tlD6XhbsHPkCQQDSVP3IbrsWs7pFkTcB3ATC32pAB71Bnn/rEJM66UE1gw1Sw81F"
+ "ZR+fKRcV4eds4RXRvCr3rlRUDZyZOlqYEMHvAkEAzoUetHoeepm7eukr+xcvu3Yu7fHiTggIijFf"
+ "2kgwnRak8APA5hAmLj9HWeeGajBY3h4pFweFoJ5vARE9OB0zrQJBALKDri2aRbHb8uGugThTy7q1"
+ "slEMAIYcB0ez9rHOXSkUxI8VXjhivnbwggZxiGDxnPo4sWMsE6iPMPUgANoFhwMCQQCqpZLmnFXd"
+ "BnTFLjDaTKFzbEeA9DMEOV0dG4lRq/8HfrORY/ib4dI6uqzxm/8UdZipCRD4541CWEfvANiuKmsN"
+ "AkAmPXJN+idylhtk2sh8pJbYWozKBGZOslaejpCLFGaDSuUFMS+DxuMl0rAGb2kbhkZybxEc4xjr"
+ "P9fm1ywStLgq";
PKCS8EncodedKeySpec encodedKeySpec = new PKCS8EncodedKeySpec(
new BASE64Decoder().decodeBuffer(privateKeyStr));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(encodedKeySpec);
Signature signature = Signature.getInstance("SHA1WithRSA");
signature.initSign(privateKey);

String toBeSignedData = "tangsi"; //需要生产签名的元数据
signature.update(toBeSignedData.getBytes("utf-8"));
byte[] signedData = signature.sign();
String sign = new BASE64Encoder().encode(signedData);
System.out.println("元数据生成的签名: " + sign);


}


}



3.第三个类VerifyData.java实现用公钥来对第二个类生成的签名对元数据进行验签

package signature;


import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.security.spec.X509EncodedKeySpec;


import org.junit.Test;


import sun.misc.BASE64Decoder;




/**
 * @author numb-tangsi
 */
public class VerifyData {


/**
* 公钥解密

* @throws IOException
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
* @throws InvalidKeyException
* @throws SignatureException
*/
@Test
public void test1() throws IOException, NoSuchAlgorithmException,
InvalidKeySpecException, InvalidKeyException, SignatureException {
// base64后的公钥串,这个串实际上应该从上一步的公钥文件publickey.keystore中读取
String publicKeyStr = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCprcOZYBGNAUWBLPVTbqFyA40aP0+U6lqzSWO7"
+ "SIjm1bYEtPnU8dpGmSC9k7jnvp2g0ss5VZamJczsdFKSA/bA9z5q/DUectF8bviAzGKNBztB9l5e"
+ "xPRS8jlAi9Lrqy4DcdeBZfYgwbuCVmONodHhLmFbBrjsnt2DgXTJWgirgwIDAQAB";
X509EncodedKeySpec encodedKeySpec = new X509EncodedKeySpec(
new BASE64Decoder().decodeBuffer(publicKeyStr));
KeyFactory keFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keFactory.generatePublic(encodedKeySpec);
Signature signature = Signature.getInstance("SHA1WithRSA");
signature.initVerify(publicKey);// 初始化公钥
String toBeVerifyData = "tangsi"; // 待验签的数据
signature.update(toBeVerifyData.getBytes("utf-8"));
String sign = "Maz4PvoJtJBf/jWWoROy56Tc9zz+ok/2BoMDY+yBtL2EclEsWp3DsW9rCUHoAevrI/zF2nNt/XfA"
+ "x1hTvm63c401Wh/gvL4/bNXQAfyxT/WvRMIMprmlRY3Opbq/0TBT+eCdggZwok3VMOje4cgUV1sr"
+ "ixFT63xCfSmDc0OrN2M=";
boolean verify = signature.verify(new BASE64Decoder()
.decodeBuffer(sign)); // 用签名来验证待验证数据的合法性,如果待验签的数据被修改过则会验证失败
System.out.println(verify);


}
}

简易SHA1函数(JavaScript实现)

Link: http://www.web-tinker.com/article/20710.html 简易SHA1函数(JavaScript实现)   据说MD5目...

Java加密-SHA算法家族(前端js,后台java)

一、概述 一、概述 SHA算法基于MD4算法基础之上,作为MD算法的继任者,成为新一代消息摘要算法的代表。SHA与MD算法不同之处主要在于摘要长度,SHA算法的摘要长度更长,安全性更高...

基于私钥加密公钥解密的RSA算法C#实现

RSA算法是第一个能同时用于加密和数字签名的算法,也易于理解和操作。 RSA是被研究得最广泛的公钥算法,从提出到现在已近二十年,经历了各种攻击的考验,逐渐为人们接受,普遍认为是目前最优秀的公钥方案之一...

android实现RSA公钥加密私钥解密工具类

客户要求要做RSA加密,以为之前没有做过,以为网上随便找个资料就可以了,哪知道都不能实现,最后找到了找个资料,希望能帮助到大家...

iOS RSA公钥加密和SHA1WithRSA私钥加签,Java服务器端解密验签demo 源码

直接上源代码,看了就清除了,不会的在联系我 package com.XX.test; import org.apache.commons.codec.binary.Base64; impor...

RSA基于Java Web的前台公钥加密后台私钥解密

RSA是目前最有影响力的公钥加密算法,它能够抵抗到目前为止已知的绝大多数密码攻击,已被ISO推荐为公钥数据加密标准。 在公开密钥密码体制中,加密密钥(即公开密钥)PK是公开信息,而解密密钥(即秘密...
  • kerryzb
  • kerryzb
  • 2016年05月26日 12:25
  • 4194
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:java 实现RSA实现数据的私钥加密以及公钥解密
举报原因:
原因补充:

(最多只允许输入30个字)