首页 > 编程语言 > 详细

数据签名标准算法-DSA (Digital signature Algorithm DSA)

时间:2015-11-05 13:23:26      阅读:218      评论:0      收藏:0      [点我收藏+]
        支持的算法有 : SHA1withDSA  224 , 256 , 384, 512 
public abstract class DSACoderSignature {

    private static final String PRIVATE_KEY = "RSAPrivate_Key";
    private static final String PUBLIC_KEY = "RSAPublic_key";

    private static final int KEY_SIZE = 1024;

    private static final String KEY_ALGORITHM = "DSA";

    private static final String SIGNATURE_ALGORITHM = "SHA1withDSA";

    public static byte[] getprivateKey(Map<String, Object> keyMap) throws Exception {
        Key key = (Key) keyMap.get(PRIVATE_KEY);
        return key.getEncoded();
    }

    public static byte[] getPublicKey(Map<String, Object> keyMap) throws Exception {
        Key key = (Key) keyMap.get(PUBLIC_KEY);
        return key.getEncoded();
    }
    
    /**
     *  生产公私钥 保存到Map里面
     * @return
     * @throws Exception
     */
    public static Map<String, Object> initKey() throws Exception {
        Map<String, Object> keyMap = new HashMap<String, Object>(2);

        KeyPairGenerator keyPaiGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);

        keyPaiGen.initialize(KEY_SIZE);

        KeyPair pair = keyPaiGen.generateKeyPair();

        DSAPublicKey publicKey = (DSAPublicKey) pair.getPublic();

        DSAPrivateKey privateKey = (DSAPrivateKey) pair.getPrivate();

        keyMap.put(PUBLIC_KEY, publicKey);
        keyMap.put(PRIVATE_KEY, privateKey);

        return keyMap;
    }

    /**
     * 用私钥生产数字签名,
     * @param data
     * @param privateKey
     * @return
     * @throws Exception
     */
    public static byte[] sign(byte[] data, byte[] privateKey) throws Exception {
        PKCS8EncodedKeySpec pkc = new PKCS8EncodedKeySpec(privateKey);

        KeyFactory keyfactory = KeyFactory.getInstance(KEY_ALGORITHM);

        PrivateKey prikey = keyfactory.generatePrivate(pkc);

        Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM);
        sig.initSign(prikey);
        sig.update(data);

        return sig.sign();
    }
    
    /**
     * 用公钥decryption,检验私钥encryption的正确性,
     * @param data
     * @param publicKey
     * @param signs  私钥生产的encryption数字证书
     * @return
     * @throws Exception
     */
    public static boolean verify(byte[] data, byte[] publicKey, byte[] signs) throws Exception {
        X509EncodedKeySpec pkc= new X509EncodedKeySpec(publicKey);

        KeyFactory keyfactory = KeyFactory.getInstance(KEY_ALGORITHM);

        PublicKey pubkey = keyfactory.generatePublic(pkc);

        Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM);

        sig.initVerify(pubkey);
        sig.update(data);

        return sig.verify(signs);
    }

}

 

数据签名标准算法-DSA (Digital signature Algorithm DSA)

原文:http://www.cnblogs.com/hqfblogs/p/4938999.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!