經典數字簽名算法---RSA

RSA數字簽名算法主要能夠分爲MD系列和SHA系列兩大類。java

MD系列:MD2withRSA、MD5withRSA。算法

SHA系列:SHA1withRSA、SHA224withRSA、SHA256withRSA、SHA384withRSA、SHA512withRSA。blog

package com.antfin.jdk8.sign;

import java.security.*;

public class SHA256withRSA {

    private static final String KEY_ALGORITHM = "RSA";
    private static final String SIGN_ALGORITHM = "SHA256withRSA";
    private static final String ENCODING = "UTF-8";
    private static final int KEY_SIZE = 2048;

    public static void main(String[] args) throws Exception {
        String data = "待簽名的數據";
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        keyPairGenerator.initialize(KEY_SIZE);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();

        Signature signature = Signature.getInstance(SIGN_ALGORITHM);
        signature.initSign(privateKey);
        signature.update(data.getBytes(ENCODING));
        byte[] bytesSign = signature.sign(); //簽名

        signature.initVerify(publicKey);
        signature.update(data.getBytes(ENCODING));
        boolean flag = signature.verify(bytesSign); //驗籤
        System.out.println("flag: "+flag);
    }
}
相關文章
相關標籤/搜索