java实现字符串非对称加密(私钥加密,公钥解密并对比)
/**
* @author cyw 创建日期: 2010-11-25
*/
package com.bean;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
public class P14_02 {
private KeyPair key = null; //公钥和私钥对
Signature sig = null;
public P14_02() throws NoSuchAlgorithmException
{
//形成DSA公钥对
KeyPairGenerator kgen = KeyPairGenerator.getInstance("DSA");
kgen.initialize(1024);
//生成公钥和私钥对
key = kgen.generateKeyPair();
//实例化signature,用于指定数字签名,指定用DSA算法
sig = Signature.getInstance("DSA");
}
public byte[] jiami(String msg) throws InvalidKeyException,SignatureException //私钥加密
{
byte[] msgBytes = msg.getBytes();
//得到私钥
PrivateKey privateKey = key.getPrivate();
//用私钥来初始化数字签名对象
sig.initSign(privateKey);
//对msgBytes 进行数字签名
sig.update(msgBytes);
//完成签名后,将放入字节数组signatureBytes
byte[] signatureBytes = sig.sign();
return signatureBytes;
}
public boolean yanzheng(String msg,byte[] signatureBytes) throws InvalidKeyException,SignatureException
{
//使用公钥验证
PublicKey publicKey = key.getPublic();
sig.initVerify(publicKey);
byte[] msgBytes2 = msg.getBytes();
//对msgBytes2 重新进行数字签名
sig.update(msgBytes2);
return sig.verify(signatureBytes);
}
public static void main(String[] args) throws Exception{
String msg = "我是一条数据";
System.out.println("原文是:"+msg);
P14_02 p14_02 = new P14_02();
byte[] signatureBytes = p14_02.jiami(msg);
//下边两行没有实际用处,是显示加密后的字符串用的
String signature1 = new String(signatureBytes);
System.out.println("签名是:"+signature1);
//
boolean a = p14_02.yanzheng(msg,signatureBytes);
if(a)
{
System.out.println("验证成功");
}
else
{
System.out.println("验证失败");
}
}