SHA1withRSA 알고리즘 을 사용 하여 서명 과 검 사 를 진행 합 니 다.

2236 단어 Java
package com.hhh.nnn.test;

import org.apache.commons.codec.binary.Base64;

import java.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;

public class EncryptionTest {

    /**
     *     ,DH          1024
     *        64   , 512 65536   
     **/
    private static final int KEY_SIZE=1024;

    public static void main(String[] args) {

        try {
            KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
            gen.initialize(KEY_SIZE);
            KeyPair pair = gen.generateKeyPair();
            // rsa       
            PublicKey publicKey = pair.getPublic();
            PrivateKey privateKey = pair.getPrivate();


            //        
            byte[] data = "sss".getBytes(StandardCharsets.UTF_8);


            // SHA1withRSA      ,RSA    
            Signature sign = Signature.getInstance("SHA1withRSA");
            sign.initSign(privateKey);
            //        
            sign.update(data);
            //       
            byte[] signature = sign.sign();



            // -----------------------------------------------
            // Base64  
            String s = new String(Base64.encodeBase64(signature));
            //        s   ,      true
            System.out.println(s);

            // Base64  ,        
            // signature = new BASE64Decoder().decodeBuffer(s);

            //                          
            signature = Base64.decodeBase64(s);

            //     ,             ,   Base64  
            // signature = s.getBytes(StandardCharsets.UTF_8); 
            // -----------------------------------------------



            // RSA    :
            Signature verifySign = Signature.getInstance("SHA1withRSA");
            verifySign.initVerify(publicKey);
            //        
            verifySign.update(data);
            //     
            boolean flag = verifySign.verify(signature);
            //    true
            System.out.println(flag);

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

좋은 웹페이지 즐겨찾기