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

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);


}
}

你可能感兴趣的:(java技术)