Java读取证书

import java.io.FileInputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import Decoder.BASE64Encoder;


public class TestRSA {

 //**************************************获取私钥******************************************************************    
    //获取私钥
    public static String GetPrivateKey()
    {
        try{
            
             KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
             
             keystore.load(new FileInputStream("C:\\Program Files\\Java\\jre7\\bin\\xiaoyaodijun.keystore"), "xxxxxx".toCharArray());

             KeyPair keyPair = getKeyPair(keystore, "xiaoyaodijun.keystore", "7391428");

             PrivateKey privateKey = keyPair.getPrivate();

              BASE64Encoder encoder=new BASE64Encoder();  
              
              String encoded=encoder.encode(privateKey.getEncoded());
              System.out.println("private key = " + encoded); 
              

              return encoded;
        }catch(Exception ex){
            return "";
        }
    }
    
    //获取KeyPair
    public static KeyPair getKeyPair(KeyStore keystore, String alias, String password) {    
        try {    
            Key key=keystore.getKey(alias,password.toCharArray());    
            if(key instanceof PrivateKey) {    
                Certificate cert=keystore.getCertificate(alias);   

                BASE64Encoder encoder=new BASE64Encoder();  

                PublicKey publicKey=cert.getPublicKey(); 

                String encoded=encoder.encode(publicKey.getEncoded());
                System.out.println("publicKey key = " + encoded); 

                return new KeyPair(publicKey,(PrivateKey)key);    
            }    
        }catch (Exception e) {    
        }    
        return null;    
    }  

    
//**************************************获取私钥******************************************************************    
    //获取公钥
    public static String GetPublicKey()
    {
        try{

            String cerPath="E:\\Java开发\\newTest\\src\\libs\\donghuangtaiyi.cer";


            X509Certificate x509Certificate = null;
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            FileInputStream fileInputStream = new FileInputStream(cerPath);
            x509Certificate = (X509Certificate) certificateFactory.generateCertificate(fileInputStream);
            fileInputStream.close();

            PublicKey publicKey = x509Certificate.getPublicKey();
            BASE64Encoder encoder=new BASE64Encoder(); 
            String encoded=encoder.encode(publicKey.getEncoded());
            System.out.println("publicKey key = " + encoded); 

            return encoded;
        }
        catch(Exception ex)
        {

            System.out.println(ex);
            return "";
        }
        
    }
    
    
    
 //************************************* 加签 ***************************************************************
    
    public static final String KEY_ALGORITHM = "RSA";

     /**
     * 校验数字签名
     * 
     * @param content 数据
     * @param privateKey私钥
     * @throws Exception
     * 
     */ 
    public static String sign(String content, String privateKey) throws Exception {
        
        byte[] data=content.getBytes("utf-8");
        
        // 解密由base64编码的私钥
        byte[] keyBytes = HashUtil.decryptBASE64(privateKey);

        // 构造PKCS8EncodedKeySpec对象
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);

        // KEY_ALGORITHM 指定的加密算法
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

        // 取私钥匙对象
        PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);

        // 用私钥对信息生成数字签名
        Signature signature = Signature.getInstance("SHA384WithRSA");
        signature.initSign(priKey);
        signature.update(data);

        return HashUtil.encryptBASE64(signature.sign());
    }

    
    
     /**
     * 校验数字签名
     * 
     * @param content 数据
     * @param publicKey公钥
     * @param sign 数字签名  
     * @return 校验成功返回true 失败返回false
     * @throws Exception
     * 
     */
    public static boolean verify(String content, String publicKey, String sign)
            throws Exception {

        byte[] data=content.getBytes("utf-8");
        
        // 解密由base64编码的公钥
        byte[] keyBytes = HashUtil.decryptBASE64(publicKey);

        // 构造X509EncodedKeySpec对象
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);

        // KEY_ALGORITHM 指定的加密算法
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

        // 取公钥匙对象
        PublicKey pubKey = keyFactory.generatePublic(keySpec);

        Signature signature = Signature.getInstance("SHA384WithRSA");
        signature.initVerify(pubKey);
        signature.update(data);

        // 验证签名是否正常
        boolean result= signature.verify(HashUtil.decryptBASE64(sign));
        return result;
    }        
}

 

 public static string ConvertEncodeBase64URLSafe(string data)
        {
            return data.Replace("=", String.Empty).Replace('+', '-').Replace('/', '_');
        }
        public static string ConvertDecodeBase64URLSafe(string data)
        {
            data = data.Replace('-', '+').Replace('_', '/');
            int len = data.Length % 4;
            if (len > 0)
            {
                data += "====".Substring(0, 4 - len);
            }
            return data;

 

posted @ 2019-01-21 23:05  逍遥帝君  阅读(6356)  评论(0编辑  收藏  举报