Kapat
Java-Https
Java 850 views 0

Java-Https link üzerinden sertifika alma ve kullanma

Java-Https link üzerinden sertifika alma ve kullanma

Java ile geliştirme yaparken https üzerinden sertifika alıp kullanmaya ihtiyaç duyabiliriz. Aşağıda bulacağınız örnek kod üzerinden aşağıda belirtilen maddeler açıklanma çalışılmıştır;

  1. Sertifikanın alınması
  2. Sertifikanın kaydedilmesi
  3. Sertifikanın doğrulanması
  4. Sertifikanın keystore da kullanılması

İlk adım olarak Keystore nesnesi ile sertifika deposunu değişkene atıyoruz(X.509 tipinde). Daha sonra güvenli url adresimize connection açıyoruz. Açılan connection nesnesi üzerinden sertifika listesini alıp döngü kuruyoruz. Kurulan döngüde doğrulamadan geçen sertifikayı alıp C: sürücüsüne file olarak atıyoruz. Daha sonrasında sertifikayı keystore a ekleyip methodumuzu tamamlamış oluyoruz.

İyi kodlamalar 🙂

private static void getCert(String HTTPS_URL) {
   try {
     KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
     trustStore.load(null);
     CertificateFactory cf = CertificateFactory.getInstance("X.509");

     URL destinationURL = new URL(HTTPS_URL);
     HttpsURLConnection conn = (HttpsURLConnection) destinationURL.openConnection();
     conn.connect();
     Certificate[] certs = conn.getServerCertificates();
     int j = 0;
     String certPath = "";
     for (Certificate certx : certs) {
       if (certx instanceof X509Certificate) {
         try {
           j++;
           ((X509Certificate) certx).checkValidity();
           certPath = "C:/sertifika" + j + ".cer";
           FileOutputStream os = new FileOutputStream(certPath);
           os.write(certx.getEncoded());
           os.close();

           //add keystore
           InputStream fis = new FileInputStream(certPath);
           BufferedInputStream bis = new BufferedInputStream(fis);
           while (bis.available() > 0) {
             Certificate cert = cf.generateCertificate(bis);
             trustStore.setCertificateEntry("sertifika" + j, cert);
           }
         } catch (CertificateExpiredException cee) {
           throw new Exception("Sertifika Süresi Dolmuş!");
         }
       } else {
         throw new Exception("Wsdl Sertifikası Sorunlu!");
       }
     }

   } catch (Exception ex) {
     ex.printStackTrace();
   }

 }

{belenyasin}

Bir Cevap Yazın