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;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM