数字签名证书

常用的Java加密技术和核心代码系列:

Base64以及关于Base64遇到的坑   https://blog.csdn.net/haponchang/article/details/106094115

消息摘要算法  https://blog.csdn.net/haponchang/article/details/106096542

对称加密(DES、3DES、AES、PBE) https://blog.csdn.net/haponchang/article/details/106096766

非对称加密(RSA、DH) https://blog.csdn.net/haponchang/article/details/106097998

数字签名证书 https://blog.csdn.net/haponchang/article/details/106098779

 

非对称加密已经灰常安全了,但是还有一个破绽:
服务器A公布了自己的公钥,我的电脑是用服务器A的公钥加密数据后再发给服务器A的;这时候服务器B侵入了我的电脑,把我用来加密的公钥换成了它的公钥,于是我发出去的数据就会被服务器B的私钥破解了。

如何防止公钥被篡改呢?
可以使用消息摘要,服务器A把公钥丢给我的时候,同时去CA申请一份数字证书,其实主要就是公钥的消息摘要,有了这份证书,当我再用公钥加密的时候,我就可以先验证一下当前的公钥是否确定是服务器A发送给我的。
 

例子:RSASign:

import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

public class RSASign {

    public static boolean verifySign(String src) {
        try {
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance ("RSA");
            keyPairGenerator.initialize (512);
            KeyPair keyPair = keyPairGenerator.generateKeyPair ( );
            PublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic ( );
            PrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate ( );

            PKCS8EncodedKeySpec pkcs8EncodedKeySpec
                    = new PKCS8EncodedKeySpec (rsaPrivateKey.getEncoded ( ));
            KeyFactory keyFactory = KeyFactory.getInstance ("RSA");
            PrivateKey privateKey = keyFactory.generatePrivate (pkcs8EncodedKeySpec);
            Signature signature = Signature.getInstance ("MD5withRSA");
            signature.initSign (privateKey);
            signature.update (src.getBytes ( ));
            //生成签名bytes
            byte[] signBytes = signature.sign ( );

            X509EncodedKeySpec x509EncodedKeySpec =
                    new X509EncodedKeySpec (rsaPublicKey.getEncoded ( ));
            keyFactory = KeyFactory.getInstance ("RSA");
            PublicKey publicKey = keyFactory.generatePublic (x509EncodedKeySpec);
            signature = Signature.getInstance ("MD5withRSA");
            signature.initVerify (publicKey);
            signature.update (src.getBytes ( ));
            boolean isVerified = signature.verify (signBytes);

            return isVerified;
        } catch (Exception e) {
            e.printStackTrace ( );
        }

        return false;
    }

}

 

你可能感兴趣的:(基础)