Java Tutorial/Security/X509Certificate

Материал из Java эксперт
Перейти к: навигация, поиск

Creating a Self-Signed Version 1 Certificate

import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.Security;
import java.security.SignatureException;
import java.security.cert.X509Certificate;
import java.util.Date;
import javax.security.auth.x500.X500Principal;
import org.bouncycastle.x509.X509V1CertificateGenerator;
public class MainClass {
  public static X509Certificate generateV1Certificate(KeyPair pair) throws InvalidKeyException,
      NoSuchProviderException, SignatureException {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(new X500Principal("CN=Test Certificate"));
    certGen.setNotBefore(new Date(System.currentTimeMillis() - 10000));
    certGen.setNotAfter(new Date(System.currentTimeMillis() + 10000));
    certGen.setSubjectDN(new X500Principal("CN=Test Certificate"));
    certGen.setPublicKey(pair.getPublic());
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
    return certGen.generateX509Certificate(pair.getPrivate(), "BC");
  }
  public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    KeyPair pair = generateRSAKeyPair();
    X509Certificate cert = generateV1Certificate(pair);
    cert.checkValidity(new Date());
    cert.verify(cert.getPublicKey());
  }
  public static KeyPair generateRSAKeyPair() throws Exception {
    KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA", "BC");
    kpGen.initialize(1024, new SecureRandom());
    return kpGen.generateKeyPair();
  }
}





Creating a Self-Signed Version 3 Certificate

import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.Security;
import java.security.SignatureException;
import java.security.cert.X509Certificate;
import java.util.Date;
import javax.security.auth.x500.X500Principal;
import org.bouncycastle.asn1.x509.BasicConstraints;
import org.bouncycastle.asn1.x509.ExtendedKeyUsage;
import org.bouncycastle.asn1.x509.GeneralName;
import org.bouncycastle.asn1.x509.GeneralNames;
import org.bouncycastle.asn1.x509.KeyPurposeId;
import org.bouncycastle.asn1.x509.KeyUsage;
import org.bouncycastle.asn1.x509.X509Extensions;
import org.bouncycastle.x509.X509V3CertificateGenerator;
public class MainClass {
  public static X509Certificate generateV3Certificate(KeyPair pair) throws InvalidKeyException,
      NoSuchProviderException, SignatureException {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(new X500Principal("CN=Test Certificate"));
    certGen.setNotBefore(new Date(System.currentTimeMillis() - 10000));
    certGen.setNotAfter(new Date(System.currentTimeMillis() + 10000));
    certGen.setSubjectDN(new X500Principal("CN=Test Certificate"));
    certGen.setPublicKey(pair.getPublic());
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
    certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature
        | KeyUsage.keyEncipherment));
    certGen.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(
        KeyPurposeId.id_kp_serverAuth));
    certGen.addExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(
        new GeneralName(GeneralName.rfc822Name, "test@test.test")));
    return certGen.generateX509Certificate(pair.getPrivate(), "BC");
  }
  public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    
    KeyPair pair = generateRSAKeyPair();
    X509Certificate cert = generateV3Certificate(pair);
    cert.checkValidity(new Date());
    cert.verify(cert.getPublicKey());
  }
  public static KeyPair generateRSAKeyPair() throws Exception {
    KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA", "BC");
    kpGen.initialize(1024, new SecureRandom());
    return kpGen.generateKeyPair();
  }
}





Display properties of X509 Certificate

import java.io.FileInputStream;
import java.math.BigInteger;
import java.security.PublicKey;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
public class MainClass {
  public static void main(String args[]) throws Exception {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    FileInputStream in = new FileInputStream(args[0]);
    java.security.cert.Certificate c = cf.generateCertificate(in);
    in.close();
    X509Certificate t = (X509Certificate) c;
    System.out.println(t.getVersion());
    System.out.println(t.getSerialNumber().toString(16));
    System.out.println(t.getSubjectDN());
    System.out.println(t.getIssuerDN());
    System.out.println(t.getNotBefore());
    System.out.println(t.getNotAfter());
    System.out.println(t.getSigAlgName());
    byte[] sig = t.getSignature();
    System.out.println(new BigInteger(sig).toString(16));
    PublicKey pk = t.getPublicKey();
    byte[] pkenc = pk.getEncoded();
    for (int i = 0; i < pkenc.length; i++) {
      System.out.print(pkenc[i] + ",");
    }
  }
}





Generate cert path for X.509

import java.io.FileInputStream;
import java.security.cert.CertPath;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
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);
    List cplist = cp.getCertificates();
    Object[] o = cplist.toArray();
    for (int i = 0; i < o.length; i++) {
      X509Certificate c = (X509Certificate) o[i];
      System.out.println(c.getSubjectDN());
      byte[] pbk = c.getPublicKey().getEncoded();
      for (int j = 0; j < pbk.length; j++) {
        System.out.print(pbk[j] + ",");
      }
      System.out.println("\nIssued by " + c.getIssuerDN());
    }
  }
}





Print out X509Certificate"s properties

import java.io.FileInputStream;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
public class MainClass {
  public static void main(String args[]) throws Exception {
    FileInputStream fr = new FileInputStream("sdo.cer");
    CertificateFactory cf = CertificateFactory.getInstance("X509");
    X509Certificate c = (X509Certificate) cf.generateCertificate(fr);
    System.out.println("\tCertificate for: " + c.getSubjectDN());
    System.out.println("\tCertificate issued by: " + c.getIssuerDN());
    System.out.println("\tThe certificate is valid from " + c.getNotBefore() + " to "
        + c.getNotAfter());
    System.out.println("\tCertificate SN# " + c.getSerialNumber());
    System.out.println("\tGenerated with " + c.getSigAlgName());
  }
}





Use X.509 certificate

import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
public class MainClass {
  public static void main(String args[]) throws Exception {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    FileInputStream in = new FileInputStream(args[0]);
    Certificate c = cf.generateCertificate(in);
    in.close();
    String s = c.toString();
    FileOutputStream fout = new FileOutputStream("tmp.txt");
    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fout));
    out.write(s, 0, s.length());
    out.close();
  }
}