RSA签名

package net.hkbn.prov.wechat.inapp.api.util;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


@Component
public class RsaSHA256 {
    
    private static String privateKey;
    
    private static String publicKey;
    

    public static byte[] signBySha256WithRsa(byte[] plain_text) throws Exception
    {
        Signature signature = Signature.getInstance("SHA256withRSA");
        signature.initSign(getPrivateKey());
        signature.update(plain_text);
        return signature.sign();
    }

    public static boolean verifySignBySha256WithRsa(byte[] plain_text, byte[] signed) throws Exception
    {
        Signature signetcheck = Signature.getInstance("SHA256withRSA");
        signetcheck.initVerify(getPublicKey());
        signetcheck.update(plain_text);
        return signetcheck.verify(signed);
    }

    
    //Get Public Key
     public static PublicKey getPublicKey() throws Exception {
         byte[] keyBytes;
         keyBytes = Base64.decodeBase64(publicKey);
         X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
         KeyFactory keyFactory = KeyFactory.getInstance("RSA");
         PublicKey publicKey = keyFactory.generatePublic(keySpec);
         return publicKey;
   }

    //Get Private Key
     public static PrivateKey getPrivateKey() throws Exception {
         byte[] keyBytes;
         keyBytes = Base64.decodeBase64(privateKey);
         PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
         KeyFactory keyFactory = KeyFactory.getInstance("RSA");
         PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
         return privateKey;
   }

    @Value("${rsa.private.key}")
    public void setPrivateKey(String privateKey) {
        RsaSHA256.privateKey = privateKey;
    }

    @Value("${rsa.public.key}")
    public void setPublicKey(String publicKey) {
        RsaSHA256.publicKey = publicKey;
    }
}
 

展开阅读全文

没有更多推荐了,返回首页