Java Tutorial/Security/Certificate

Материал из Java эксперт
Версия от 05:01, 1 июня 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Creating a Certificate in Java

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.util.Date;
import sun.security.x509.AlgorithmId;
import sun.security.x509.CertificateAlgorithmId;
import sun.security.x509.CertificateIssuerName;
import sun.security.x509.CertificateSerialNumber;
import sun.security.x509.CertificateSubjectName;
import sun.security.x509.CertificateValidity;
import sun.security.x509.X500Name;
import sun.security.x509.X509CertImpl;
import sun.security.x509.X509CertInfo;
public class MainClass {
  public static void main(String[] args) throws Exception {
    String keystoreFile = "keyStoreFile.bin";
    String caAlias = "caAlias";
    String certToSignAlias = "cert";
    String newAlias = "newAlias";
    char[] password = new char[]{"a","b","c","d","e","f","g","h"};
    char[] caPassword = new char[]{"a","b","c","d","e","f","g","h"};
    char[] certPassword = new char[]{"a","b","c","d","e","f","g","h"};
    FileInputStream input = new FileInputStream(keystoreFile);
    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(input, password);
    input.close();
    PrivateKey caPrivateKey = (PrivateKey) keyStore.getKey(caAlias, caPassword);
    java.security.cert.Certificate caCert = keyStore.getCertificate(caAlias);
    byte[] encoded = caCert.getEncoded();
    X509CertImpl caCertImpl = new X509CertImpl(encoded);
    X509CertInfo caCertInfo = (X509CertInfo) caCertImpl.get(X509CertImpl.NAME + "."
        + X509CertImpl.INFO);
    X500Name issuer = (X500Name) caCertInfo.get(X509CertInfo.SUBJECT + "."
        + CertificateIssuerName.DN_NAME);
    java.security.cert.Certificate cert = keyStore.getCertificate(certToSignAlias);
    PrivateKey privateKey = (PrivateKey) keyStore.getKey(certToSignAlias, certPassword);
    encoded = cert.getEncoded();
    X509CertImpl certImpl = new X509CertImpl(encoded);
    X509CertInfo certInfo = (X509CertInfo) certImpl
        .get(X509CertImpl.NAME + "." + X509CertImpl.INFO);
    Date firstDate = new Date();
    Date lastDate = new Date(firstDate.getTime() + 365 * 24 * 60 * 60 * 1000L);
    CertificateValidity interval = new CertificateValidity(firstDate, lastDate);
    certInfo.set(X509CertInfo.VALIDITY, interval);
    certInfo.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(
        (int) (firstDate.getTime() / 1000)));
    certInfo.set(X509CertInfo.ISSUER + "." + CertificateSubjectName.DN_NAME, issuer);
    AlgorithmId algorithm = new AlgorithmId(AlgorithmId.md5WithRSAEncryption_oid);
    certInfo.set(CertificateAlgorithmId.NAME + "." + CertificateAlgorithmId.ALGORITHM, algorithm);
    X509CertImpl newCert = new X509CertImpl(certInfo);
    newCert.sign(caPrivateKey, "MD5WithRSA");
    keyStore.setKeyEntry(newAlias, privateKey, certPassword,
        new java.security.cert.Certificate[] { newCert });
    FileOutputStream output = new FileOutputStream(keystoreFile);
    keyStore.store(output, password);
    output.close();
  }
}





Exporting a Certificate to a File

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.security.KeyStore;
import java.security.cert.Certificate;
public class Main {
  public static void main(String[] argv) throws Exception {
    FileInputStream is = new FileInputStream("your.keystore");
    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    keystore.load(is, "my-keystore-password".toCharArray());
    String alias = "myalias";
    Certificate cert = keystore.getCertificate(alias);
    File file = null;
    byte[] buf = cert.getEncoded();
    FileOutputStream os = new FileOutputStream(file);
    os.write(buf);
    os.close();
    Writer wr = new OutputStreamWriter(os, Charset.forName("UTF-8"));
    wr.write(new sun.misc.BASE64Encoder().encode(buf));
    wr.flush();
  }
}





Generate X.509 certificate

import java.io.FileInputStream;
import java.security.cert.CertPath;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.util.ArrayList;
import java.util.List;
public class MainClass {
  public static void main(String args[]) throws Exception {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    List mylist = new ArrayList();
    for (int i = 0; i < args.length; i++) {
      FileInputStream in = new FileInputStream(args[i]);
      Certificate c = cf.generateCertificate(in);
      mylist.add(c);
    }
    CertPath cp = cf.generateCertPath(mylist);
    System.out.println(cp);
  }
}





Import certificate

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.CertificateFactory;
public class MainClass {
  public static void main(String args[]) throws Exception {
    String cacert = "mytest.cer";
    String lfcert = "lf_signed.cer";
    String lfstore = "lfkeystore";
    char[] lfstorepass = "wshr.ut".toCharArray();
    char[] lfkeypass = "wshr.ut".toCharArray();
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    FileInputStream in1 = new FileInputStream(cacert);
    java.security.cert.Certificate cac = cf.generateCertificate(in1);
    in1.close();
    FileInputStream in2 = new FileInputStream(lfcert);
    java.security.cert.Certificate lfc = cf.generateCertificate(in2);
    in2.close();
    java.security.cert.Certificate[] cchain = { lfc, cac };
    FileInputStream in3 = new FileInputStream(lfstore);
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(in3, lfstorepass);
    PrivateKey prk = (PrivateKey) ks.getKey("lf", lfkeypass);
    ks.setKeyEntry("lf_signed", prk, lfstorepass, cchain);
    FileOutputStream out4 = new FileOutputStream("lfnewstore");
    ks.store(out4, "newpass".toCharArray());
    out4.close();
  }
}





KeyStore Example

import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.cert.Certificate;
public class MainClass {
  public static void main(String[] args) throws Exception {
    String keystoreFilename = "my.keystore";
    char[] password = "password".toCharArray();
    String alias = "alias";
    FileInputStream fIn = new FileInputStream(keystoreFilename);
    KeyStore keystore = KeyStore.getInstance("JKS");
    keystore.load(fIn, password);
    Certificate cert = keystore.getCertificate(alias);
    System.out.println(cert);
  }
}





Store Certificate

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.security.KeyStore;
import java.security.cert.CertPath;
import java.security.cert.X509Certificate;
import java.util.List;
public class MainClass {
  public static void main(String args[]) throws Exception {
    FileInputStream f = new FileInputStream("CertPath.dat");
    ObjectInputStream b = new ObjectInputStream(f);
    CertPath cp = (CertPath) b.readObject();
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);
    List cplist = cp.getCertificates();
    Object[] o = cplist.toArray();
    for (int i = 0; i < o.length; i++) {
      X509Certificate c = (X509Certificate) o[i];
      ks.setCertificateEntry("my" + i, c);
    }
    FileOutputStream output = new FileOutputStream("MyCertPathStore");
    ks.store(output, "mypass".toCharArray());
    output.close();
  }
}





Using Certificates in Java

import java.io.FileInputStream;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
public class MainClass {
  public static void main(String[] args) throws Exception {
    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    FileInputStream fis = new FileInputStream("a.dat");
    Certificate cert = certFactory.generateCertificate(fis);
    fis.close();
    System.out.println(cert);
  }
}





Validate certificate

import java.io.FileInputStream;
import java.security.cert.CertPath;
import java.security.cert.CertPathValidator;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.PKIXCertPathValidatorResult;
import java.security.cert.PKIXParameters;
import java.security.cert.TrustAnchor;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class MainClass {
  public static void main(String args[]) throws Exception {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    List mylist = new ArrayList();
    FileInputStream in = new FileInputStream(args[0]);
    Certificate c = cf.generateCertificate(in);
    mylist.add(c);
    CertPath cp = cf.generateCertPath(mylist);
    Certificate trust = cf.generateCertificate(in);
    TrustAnchor anchor = new TrustAnchor((X509Certificate) trust, null);
    PKIXParameters params = new PKIXParameters(Collections.singleton(anchor));
    params.setRevocationEnabled(false);
    CertPathValidator cpv = CertPathValidator.getInstance("PKIX");
    PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult) cpv.validate(cp, params);
    System.out.println(result);
  }
}





Validating a Certification Path using the most-trusted CAs in the JDK"s cacerts file.

import java.io.File;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.cert.CertPath;
import java.security.cert.CertPathValidator;
import java.security.cert.CertPathValidatorResult;
import java.security.cert.PKIXCertPathValidatorResult;
import java.security.cert.PKIXParameters;
import java.security.cert.TrustAnchor;
import java.security.cert.X509Certificate;
public class Main {
  public static void main(String[] argv) throws Exception {
    String filename = System.getProperty("java.home")
        + "/lib/security/cacerts".replace("/", File.separatorChar);
    FileInputStream is = new FileInputStream(filename);
    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    String password = "password";
    keystore.load(is, password.toCharArray());
    PKIXParameters params = new PKIXParameters(keystore);
    params.setRevocationEnabled(false);
    CertPathValidator certPathValidator = CertPathValidator.getInstance(CertPathValidator
        .getDefaultType());
    CertPath certPath = null;
    CertPathValidatorResult result = certPathValidator.validate(certPath, params);
    PKIXCertPathValidatorResult pkixResult = (PKIXCertPathValidatorResult) result;
    TrustAnchor ta = pkixResult.getTrustAnchor();
    X509Certificate cert = ta.getTrustedCert();
  }
}