JAVA加密算法(5)- 数字签名算法(RSA、DSA)

数字签名流程

(1)生成签名:对源文件的「数字摘要」,使用私钥加密,生成「加密数字摘要」;

(2)验证签名:对「加密数字摘要」通过公钥进行解密,生成「数字摘要2」,比较「数字摘要」与「数字摘要2」,结果相同则签名验证通过。

概念:带有「公钥」和「私钥」的「消息摘要」算法,是「非对称加密算法」和「消息摘要」算法的结合体

私钥签名,公钥验证

常用签名算法

  • RSASignature

  • DSASignature

  • ECDSASignature(需Bouncy Castle)

数字签名作用

  • 验证数据完整性

  • 认证数据来源

  • 抗否认

场景

如Android App开发者签名

RSASignature示例

import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

public class RSASignatureUtil {

    public static final String KEY_ALGORITHM = "RSA";//密钥算法
    public static final String SIGN_ALGORITHM = "MD5withRSA";//签名算法:MD2withRSA,SHA1WithRSA,SHA256withRSA,SHA384withRSA,SHA512withRSA

    /**
     * 初始化RSA公钥私钥
     */
    public static KeyPair initKey() throws Exception{
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        keyPairGenerator.initialize(1024);
        return keyPairGenerator.generateKeyPair();
    }

    /**
     * 签名(原数据,私钥 2要素)
     */
    public static byte[] sign(byte[] data, PrivateKey privateKey) throws Exception{
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded());
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        PrivateKey priKey = keyFactory.generatePrivate(keySpec);

        Signature signature = Signature.getInstance(SIGN_ALGORITHM);
        signature.initSign(priKey);
        signature.update(data);//设置要计算的数据
        return signature.sign();
    }

    /**
     * 校验签名(元数据,公钥,签名 三要素)
     */
    public static boolean valid(byte[] data, byte[] publicKey, byte[] sign) throws Exception{
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);
        PublicKey pubKey = keyFactory.generatePublic(keySpec);

        Signature signature = Signature.getInstance(SIGN_ALGORITHM);
        signature.initVerify(pubKey);
        signature.update(data);
        return signature.verify(sign);
    }

    public static void main(String[] args) throws Exception {
        String data = "123456";
        KeyPair keyPair = initKey();
        byte[] sign = sign(data.getBytes(),keyPair.getPrivate());
        boolean isValid = valid(data.getBytes(),keyPair.getPublic().getEncoded(),sign);
        System.out.println(isValid);
    }

}

你可能感兴趣的:(密码学,java)