pki java相關代碼參考

keytool -genkey -dname "CN=demo, OU=softDept, O=company, L=puddong,S=shanghai, C=cn" -alias demo -keyalg RSA -keysize 1024 -keystore demoKeystore -validity 3650 -storepass storePwd -keypass demoPwd
生成保存公鑰和私鑰的密鑰倉庫,保存在demoKeystore文件中。這裏storepass 和 keypass 不要有java 正則表達式中的特殊字符,否則程序裏要轉義麻煩。

keytool -export -alias demo -keystore demoKeystore -rfc -file demo.cer //從密鑰倉庫中導出保存公鑰的證書
輸入keypass 即demoPwd 


  try{     
   // 密鑰倉庫
   KeyStore ks = KeyStore.getInstance("JKS");
//讀取密鑰倉庫
   FileInputStream ksfis = new FileInputStream("demoKeystore");
   BufferedInputStream ksbufin = new BufferedInputStream(ksfis);
   char[] storePwd = "storePwd".toCharArray();
   ks.load(ksbufin, storePwd);
   ksbufin.close();
   char[] keyPwd = "demoPwd".toCharArray();
//從密鑰倉庫得到私鑰
   PrivateKey priK = (PrivateKey) ks.getKey("demo", keyPwd);  
//生成cipher
   Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding",new org.bouncycastle.jce.provider.BouncyCastleProvider());
//用私鑰初始化cipher
   cipher.init(Cipher.ENCRYPT_MODE, priK);
   byte[] plain = "This is plain text".getBytes("UTF-8");
   
   // 因爲用的1024位rsa算法,一次只能加密1024/8-11字節數據,分開加密
   byte[] code = new byte[(((plain.length-1)/117+1))*128];  
            int ixplain = 0;
            int ixcode = 0;
            while((plain.length - ixplain) > 117) {//每117字節做一次加密
                ixcode += cipher.doFinal(plain, ixplain, 117, code, ixcode);
                ixplain += 117;
            }
            cipher.doFinal(plain, ixplain, plain.length - ixplain, code, ixcode);
            //加密後的code
            System.out.println(Arrays.toString(code));
            //通常會用base64編碼
           String base64 = encoder.encode(code);

   CertificateFactory certificatefactory = CertificateFactory
     .getInstance("X.509");
   // 讀取證書
   FileInputStream fin = new FileInputStream("demo.cer");
   X509Certificate certificate = (X509Certificate) certificatefactory
     .generateCertificate(fin);
   fin.close();
   // 得到公鑰
   PublicKey pubK = certificate.getPublicKey();
         //初始 化cipher
            cipher.init(Cipher.DECRYPT_MODE, pubK);
      //base64 解碼
            code = decoder.decodeBuffer(base64);
            System.out.println(Arrays.toString(code));
            byte[] plain2 = new byte[code.length];
            int ixplain2 = 0;
            int ixcode2 = 0;
            while((code.length - ixcode2) > 128) {//每128字節做一次解密
                ixplain2 += cipher.doFinal(code, ixcode2, 128, plain2, ixplain2);
                ixcode2 += 128;
            }
            ixplain2 += cipher.doFinal(code, ixcode2, code.length - ixcode2, plain2, ixplain2);
            String s2 = new String(plain2, 0, ixplain2, "UTF-8");
            System.out.println(s2);
   
  }catch(Exception ex){
   ex.printStackTrace();
  }

 

http://www.blogjava.net/neumqp/archive/2006/03/02/33211.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章