欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

DSA数字签名例子

程序员文章站 2024-03-19 14:14:52
...

1、DSA公钥私钥生成类:

import java.io.FileNotFoundException;   
import java.io.FileOutputStream;   
import java.io.IOException;   
import java.io.ObjectOutputStream;   
import java.security.KeyPair;   
import java.security.KeyPairGenerator;   
import java.security.NoSuchAlgorithmException;   
import java.security.SecureRandom;   
  
/**
 * <p>
 * Title:  * 生成DSA**对的工具类  
 * 使用方法:java DSAKeyPairGenerator -genkey public.key private.key  
 * public.key--生成的公钥文件名  
 * private.key--生成的私钥文件名  
 * </p>
 * 
 * <p>
 * Description: 
 * </p>
 * 
 * <p>
 * Copyright: 融博技术有限公司 2012
 * </p>
 * 
 * @author 袁泉锋HO174959
 * @version 1.0
 * @date Jul 30, 2012
 *
 */
public class DSAKeyPairGenerator {   
    private static final int KEYSIZE=512;   
    /**  
     * 生成DSA**对的工具类  
     * 使用方法:java DSAKeyPairGenerator -genkey public.key private.key  
     * public.key--生成的公钥文件名  
     * private.key--生成的私钥文件名  
     * @param args  
     */  
    public static void main(String[] args) {   
        if(args[0].equals("-genkey")){   
            try {   
                KeyPairGenerator pairgen=KeyPairGenerator.getInstance("DSA");   
                SecureRandom random=new SecureRandom();   
                pairgen.initialize(KEYSIZE, random);   
                KeyPair keyPair=pairgen.generateKeyPair();   
                   
                ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream(args[1]));   
                out.writeObject(keyPair.getPublic());   
                out.close();   
                   
                out=new ObjectOutputStream(new FileOutputStream(args[2]));   
                out.writeObject(keyPair.getPrivate());   
                out.close();   
            } catch (NoSuchAlgorithmException e) {   
                // TODO 自动生成 catch 块   
                e.printStackTrace();   
            } catch (FileNotFoundException e) {   
                // TODO 自动生成 catch 块   
                e.printStackTrace();   
            } catch (IOException e) {   
                // TODO 自动生成 catch 块   
                e.printStackTrace();   
            }   
        }   
    }   
  
}  

 

 

2、DSA服务类

import java.io.ObjectInputStream;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
  
  
/**
 * <p>
 * Title: 签名服务类
 * </p>
 * 
 * <p>
 * Description: 
 * </p>
 * 
 * <p>
 * Copyright: 融博技术有限公司 2012
 * </p>
 * 
 * @author 袁泉锋HO174959
 * @version 1.0
 * @date Jul 30, 2012
 *
 */
public class DSAService {   
	private PublicKey publicKey;    //公钥  给对方的
    private PrivateKey privateKey;    //私钥  自己保存好
	public DSAService() throws Exception	{
		try {   
            ObjectInputStream keyIn = new ObjectInputStream(DSAService.class.getResourceAsStream("/bb.key"));   
            privateKey = (PrivateKey) keyIn.readObject();   
            keyIn.close();   
            ObjectInputStream keyIn2 = new ObjectInputStream(DSAService.class.getResourceAsStream("/aa.key")); 
            publicKey = (PublicKey) keyIn2.readObject();   
            keyIn2.close();   
		} catch (Exception e) {   
            throw e;   
        }   
	}
    /**
     * <Description>对内容进行签名
     *
     * @since Jul 30, 2012
     * @param content
     * @return
     * @throws Exception <Description>
     *
     */
    public String sign(String content) throws Exception {   
        try {   
            Signature signalg = Signature.getInstance("DSA");   
            signalg.initSign(privateKey);   
            signalg.update(content.getBytes());   
            byte[] signature = signalg.sign();   
            return encodeHex(signature);   
        } catch (Exception e) {   
        	e.printStackTrace();
            throw e;   
        }   
    }   
  
    /**
     * <Description>对明文进行验签,确定contecnt是否是对方的信息
     *
     * @since Jul 30, 2012
     * @param signature
     * @param contecnt
     * @return
     * @throws Exception <Description>
     *
     */
    public boolean verify(String signature, String contecnt) throws Exception {   
        try {   
            Signature verifyalg = Signature.getInstance("DSA");   
            verifyalg.initVerify(publicKey);   
  
            verifyalg.update(contecnt.getBytes());   
  
            return verifyalg.verify(decodeHex(signature));   
        } catch (Exception e) {   
        	e.printStackTrace();
        	throw e;   
        }   
    }   
    /**
     * <Description>把二进制对象转化为16进制串(用字符串表示)
     *
     * @since Jul 30, 2012
     * @param bytes
     * @return <Description>
     *
     */
    private  String encodeHex(byte[] bytes) {
		StringBuffer buf = new StringBuffer(bytes.length * 2);
		for (int i = 0; i < bytes.length; ++i) {
			if ((bytes[i] & 0xFF) < 16) {
				buf.append("0");
			}
			buf.append(Long.toString(bytes[i] & 0xFF, 16));
		}
		return buf.toString();
	}
    /**
     * <Description>把字符串(该串标表示的是16进制)转化为二进制对象
     *
     * @since Jul 30, 2012
     * @param hex
     * @return <Description>
     *
     */
    private byte[] decodeHex(String hex) {
		char[] chars = hex.toCharArray();
		byte[] bytes = new byte[chars.length / 2];
		int byteCount = 0;
		for (int i = 0; i < chars.length; i += 2) {
			byte newByte = 0;
			newByte = (byte) (newByte | hexCharToByte(chars[i]));
			newByte = (byte) (newByte << 4);
			newByte = (byte) (newByte | hexCharToByte(chars[(i + 1)]));
			bytes[byteCount] = newByte;
			++byteCount;
		}
		return bytes;
	}
	private byte hexCharToByte(char ch) {
		switch (ch) {
		case '0':
			return 0;
		case '1':
			return 1;
		case '2':
			return 2;
		case '3':
			return 3;
		case '4':
			return 4;
		case '5':
			return 5;
		case '6':
			return 6;
		case '7':
			return 7;
		case '8':
			return 8;
		case '9':
			return 9;
		case 'a':
			return 10;
		case 'b':
			return 11;
		case 'c':
			return 12;
		case 'd':
			return 13;
		case 'e':
			return 14;
		case 'f':
			return 15;
		}
		return 0;
	}
	public static void main(String[] aa){
		try {
			DSAService ss = new DSAService();
			String dd = ss.sign("yqf"); //对"yqf"签名
			System.out.println(dd); //签名后
			boolean isSucc = ss.verify(dd, "yqf"); //对明文进行验签
			System.out.println(isSucc); 
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	} 
}  

 

 

 

通过例子,不难发现,DSA只能做签名,不是做加密用的。

签名是什么概念,就是说,你收到一个东西,你要验证下是不是你希望的那个人发送过来的,否则我不要,这就是签名。