RsaUtil 生成公私钥

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

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

import com.froad.openapi.util.RSAUtil;
import com.froad.platform.logger.Logger;
import com.froad.platform.logger.LoggerManager;

public class RsaUtil {
   
    private static Logger Log = LoggerManager.getLogger(RsaUtil.class.getName());
   
    /**
      * 方法描述:初始化私钥
      * @param: String str
      * @return: PublicKey
      * @version: 1.0
        * @time: 2011-12-7 上午9:11:15
      */
    public static PrivateKey initPrivateKey(String path, String pwd) {
        try {
           
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
           
            File file = new File(path);
            byte[] b = null;

            InputStream in = new FileInputStream(file);

            PKCS8Key pkcs8 = new PKCS8Key(in, pwd.toCharArray());

            b = pkcs8.getDecryptedBytes();

            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(b);

            PrivateKey prikey = keyFactory.generatePrivate(keySpec);

            return prikey;
           
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            Log.info("初始化私钥无此算法");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Log.info("初始化私钥文件未找到");
        } catch (GeneralSecurityException e) {
            Log.info("初始化私钥安全异常");
            e.printStackTrace();
        } catch (IOException e) {
            Log.info("初始化私钥IO异常");
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
            Log.info("初始化私钥异常");
        }
        return null;
    }
   
    /**
      * 方法描述:初始化公钥
      * @param: String str
      * @return: PublicKey
      * @version: 1.0
      * @time: 2011-12-7 上午9:11:15
      */
    public static PublicKey initPublicKey(String str) {
        KeyFactory keyFactory;
        try {
            keyFactory = KeyFactory.getInstance("RSA");

            X509EncodedKeySpec keySpec = new X509EncodedKeySpec((Base64.decodeBase64(str)));

            PublicKey pubkey = keyFactory.generatePublic(keySpec);

            return pubkey;

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            Log.info("初始化公钥无此算法");
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
            Log.info("初始化公钥无效的密钥规范");
        } catch (Exception e) {
            e.printStackTrace();
            Log.info("初始化公钥异常");
        }
        return null;
    }

    /**
      * 方法描述:签名
      * @param: String content, PrivateKey key, String charsetSet
      * @return: String
      * @version: 1.0
      * @time: 2011-12-7 上午9:12:48
      */
    public static String signPrivateKey(String content, PrivateKey key, String charsetSet) throws NoSuchAlgorithmException,
            IOException, InvalidKeySpecException, InvalidKeyException, SignatureException {
        PrivateKey prikey = key;

        Signature signature = Signature.getInstance("SHA1WithRSA");

        signature.initSign(prikey);

        signature.update(content.getBytes(charsetSet));

        byte[] signBytes = signature.sign();

        String sign = new String(Base64.encodeBase64(signBytes));
        return sign;
    }

    /**
      * 方法描述:验签
      * @param: String content, String sign,PublicKey key,String charsetSet
      * @return: boolean
      * @version: 1.0
      * @time: 2011-12-7 上午9:28:04
      */
    public static boolean verifyPublicKey(String content, String sign, PublicKey key,
            String charsetSet) throws NoSuchAlgorithmException, IOException,
            InvalidKeySpecException, InvalidKeyException, SignatureException {
        PublicKey pubkey = key;

        byte[] signed = Base64.decodeBase64(sign.getBytes());

        Signature signature = Signature.getInstance("SHA1WithRSA");

        signature.initVerify(pubkey);

        signature.update(content.getBytes(charsetSet));

        return signature.verify(signed);
    }

    /**
      * 方法描述:签名
      * @param: String content, PrivateKey key
      * @return: String
      * @version: 1.0
       * @time: 2011-12-7 上午9:22:21
      */
    public static String signPrivateKey(String content, PrivateKey key) throws NoSuchAlgorithmException, IOException,
    InvalidKeySpecException, InvalidKeyException, SignatureException {
        PrivateKey prikey = key;

        Signature signature = Signature.getInstance("SHA1WithRSA");
        signature.initSign(prikey);
        signature.update(content.getBytes("UTF-8"));
        byte[] signBytes = signature.sign();
        String sign = new String(Base64.encodeBase64(signBytes));
       
        return sign;
    }

    /**
      * 方法描述:验签
      * @param: String content, String sign,PublicKey key
      * @return: boolean
      * @version: 1.0
      * @time: 2011-12-7 上午9:25:05
      */
    public static boolean verifyPublicKey(String content, String sign, PublicKey key)
            throws NoSuchAlgorithmException, IOException,
            InvalidKeySpecException, InvalidKeyException, SignatureException {
        PublicKey pubkey = key;

        byte[] signed = Base64.decodeBase64(sign.getBytes());

        Signature signature = Signature.getInstance("SHA1WithRSA");

        signature.initVerify(pubkey);

        signature.update(content.getBytes("UTF-8"));

        return signature.verify(signed);
    }
    public static void main(String[] args) throws InvalidKeyException, NoSuchAlgorithmException, Exception, Exception, Exception {
        String sr = "dasasdas";
        PrivateKey pk = initPrivateKey("D:\\secretkey\\OpenSSL\\bin\\test_private_key.key", "12345");
        String msg = signPrivateKey(sr, pk,"utf-8");
        System.out.println(msg);
       
//        String publickey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDhaRco+RYyPOmnTmT+YO6svwP9bZoNY0mWm4/saGfRbWVeIleoxOKMII7S3/ZG1816pB2OJ04hT0DCad/kcPdyh1uCgISKQa5mhZfnzuNEV4P+IJM5GITf7h6PRIhOZD+XwpZbjYKyon+NJQyUdNtQslnJ+dOM8Gi59o7aGYXtAQIDAQAB";
       
        PublicKey pubk = initPublicKey("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCp25k4FVKXP8uhTCykknGKRWpNWonmBWuqFx2ZdWJ+pzw9ndg957X8kAXSeyii0Bef2hXWRJwdveY//XuEdRRuQr99ycOHuiSwj4Mt6S/nKf7unDWKBeVEGcSXBQNQEciiCFOVb7stSkqQ2aBms6uHQexeTjz7MFKsXT3cFBwCpwIDAQAB");
       
        boolean b = verifyPublicKey(sr, msg, pubk);
       
        System.out.println(b);
    }
}

你可能感兴趣的:(util)