码迷,mamicode.com
首页 > 编程语言 > 详细

java DSA Signature Sign And Verify

时间:2015-06-15 18:12:07      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:

SignatureSignAndVerify

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Security;
import java.security.Signature;

public class SignatureSignAndVerify {

      public static void main(String args[]) throws Exception {
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

        KeyPair keyPair = generateKeyPair(999);

        byte[] data = { 65, 66, 67, 68, 69, 70, 71, 72, 73, 74 };
        byte[] digitalSignature = signData(data, keyPair.getPrivate());

        boolean verified;

        verified = verifySig(data, keyPair.getPublic(), digitalSignature);
        System.out.println(verified) ;

        keyPair = generateKeyPair(888);
        verified = verifySig(data, keyPair.getPublic(), digitalSignature);
        System.out.println(verified);

      }

      public static byte[] signData(byte[] data, PrivateKey key) throws Exception {
        Signature signer = Signature.getInstance("SHA1withDSA");
        signer.initSign(key);
        signer.update(data);
        return (signer.sign());
      }

      public static boolean verifySig(byte[] data, PublicKey key, byte[] sig) throws Exception {
        Signature signer = Signature.getInstance("SHA1withDSA");
        signer.initVerify(key);
        signer.update(data);
        return (signer.verify(sig));

      }

      public static KeyPair generateKeyPair(long seed) throws Exception {
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
        KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance("DSA");
        SecureRandom rng = SecureRandom.getInstance("SHA1PRNG", "SUN");
        rng.setSeed(seed);
        keyGenerator.initialize(1024, rng);

        return (keyGenerator.generateKeyPair());
      }
}

 

java DSA Signature Sign And Verify

标签:

原文地址:http://www.cnblogs.com/rojas/p/4578466.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!