在加密和签名中使用数字证书

11 篇文章 0 订阅

在加密和签名中使用数字证书

如果你对数字签名还不熟悉,请先阅读《数字签名简介》,《Java的数字签名和数字证书

本示例程序使用的keystore文件 robin.keystore 和数字证书文件 robin.crt 都是《 数字证书简介 》中相应的命令生成的。
如果你对如何生成 keystore文件或 数字证书文件请先阅读该文。
SignatureDemo文件
package com.robin.Signature;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

public class SignatureDemo{
public SignatureDemo()
{
init();
Sender sender=new Sender();
sender.doWork();
Receiver receiver=new Receiver();
receiver.doWork();
}
void init() {
}
Message sendingMsg;
void sendMsg(Message sendMsg)
{
sendingMsg=sendMsg;
System.out.println("sending Message");
}
Message getReceivedMsg()
{
System.out.println("receiving Message");
return sendingMsg;
}
class Sender {
private final static String  keyStorePath = " robin.keystore";
private final static String  keyStorePassword = " GL2009";
private final static String  privateKeyPassword = " gl2009";
private final static String  keyStoreAlias = " robin";
// belong to sender,it is only visible to sender
private PrivateKey privateKey;
Signature sign;
Sender()
{
init();
}
private void init() {
KeyStore keyStore = null;
try {
keyStore = KeyStore.getInstance("JKS");
}  catch (KeyStoreException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
FileInputStream is = null;
try {
is = new FileInputStream(keyStorePath);
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedInputStream  bis= new BufferedInputStream(is);
try {
//读取KeyStore文件
keyStore.load(bis, keyStorePassword.toCharArray());
catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
catch (CertificateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
//读取私钥
privateKey =  (PrivateKey) keyStore.getKey(keyStoreAlias, privateKeyPassword.toCharArray());
catch (UnrecoverableKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
catch (KeyStoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}  catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
X509Certificate cert=null;
try {
cert = (X509Certificate)keyStore.getCertificate("robin");
catch (KeyStoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return;
}
try {
//从数字证书中取得签名算法
sign = Signature.getInstance(cert.getSigAlgName());
catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
void doWork() {
String words = "This is robin.How are you?";
SecretMessage msg = new SecretMessage(words.getBytes());
//对消息体进行加密
msg. crypt( privateKey);
try {
// 设置加密散列码用的私钥
sign.initSign(privateKey);
catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
// 设置散列算法的输入
sign.update(msg.getBody());
catch (SignatureException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte data[] = null;
try {
// 进行散列,对产生的散列码进行加密并返回
data =  sign.sign();
catch (SignatureException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 把加密后散列码(即签名)加到消息中
msg.setSignature(data);
// 发送消息
sendMsg(msg);
}
}//end Sender
class Receiver {
public PublicKey  publicKey;
Signature  sign;
public X509Certificate  certificate;
final static String certName = " robin.crt";
Receiver()
{
init();
}
private void init()
{
CertificateFactory certificatefactory = null;
try {
certificatefactory = CertificateFactory.getInstance("X.509");
catch (CertificateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileInputStream fin = null;
try {
fin = new FileInputStream(certName);
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
certificate = (X509Certificate) certificatefactory
.generateCertificate(fin);
catch (CertificateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
publicKey= certificate.getPublicKey();
try {
//从证书中取得签名算法
sign = Signature.getInstance( certificate.getSigAlgName() );
catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
void doWork() {
// 收到消息
SecretMessage msg = (SecretMessage)getReceivedMsg();
try {
// 设置解密散列码用的公钥。
sign.initVerify(publicKey);
catch (InvalidKeyException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
// 设置散列算法的输入
sign.update(msg.getBody());
catch (SignatureException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
/*
 * 进行散列计算,比较计算所得散列码是否和解密的散列码是否一致。 一致则验证成功,否则失败
 */
if ( sign.verify( msg.getSignature() )) {
System.out.println("数字签名验证成功!");
} else {
System.out.println("数字签名验证失败!");
}
catch (SignatureException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//对消息体进行解密
msg.decrypt(publicKey);
System.out.println("I just get a message:"+new String(msg.getBody()));
}
}// end Receiver
}

Message.java文件
package com.robin.Signature;
public class Message {
protected byte[]  body;
private byte[]  signature;
Message( byte data[]) {
body = data;
}
byte[] getBody() {
return  body;
}
byte[] getSignature() {
return  signature;
}
void setSignature( byte data[]) {
signature = data;
}
}
SecretMessage文件
package com.robin.Signature;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
public class SecretMessage extends Message {
SecretMessage( byte[] data) {
super(data);
}
public void crypt(Key key) {
byte data[] =  body;
Cipher cipher=null;
try {
cipher = Cipher.getInstance(key.getAlgorithm());
catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return;
}
try {
cipher.init(Cipher.ENCRYPT_MODE, key);
catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
data = cipher.doFinal(data);
catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
body = data;
}
public void decrypt(Key key) {
byte data[] =  body;
Cipher cipher=null;
try {
cipher = Cipher.getInstance(key.getAlgorithm());
catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return;
}
try {
cipher.init(Cipher.DECRYPT_MODE, key);
catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
data = cipher.doFinal(data);
catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
body = data;
}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值