欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

sssocket

程序员文章站 2022-03-23 21:52:44
...

package com.anyec.webmq;

 

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileReader;

import java.io.IOException;

import java.io.InputStream;

import java.security.Key;

import java.security.KeyFactory;

import java.security.KeyManagementException;

import java.security.KeyPair;

import java.security.KeyStore;

import java.security.KeyStoreException;

import java.security.NoSuchAlgorithmException;

import java.security.PrivateKey;

import java.security.Provider;

import java.security.PublicKey;

import java.security.Security;

import java.security.UnrecoverableKeyException;

import java.security.cert.Certificate;

import java.security.cert.CertificateException;

import java.security.cert.CertificateFactory;

import java.security.cert.X509Certificate;

import java.security.spec.InvalidKeySpecException;

import java.security.spec.PKCS8EncodedKeySpec;

import java.security.spec.X509EncodedKeySpec;

import javax.net.ssl.KeyManagerFactory;

import javax.net.ssl.SSLContext;

import javax.net.ssl.SSLSocketFactory;

import javax.net.ssl.TrustManagerFactory;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import org.bouncycastle.util.io.pem.PemReader;

 

public class SSLFellow {

  public static SSLSocketFactory createSSLSocketFactory(String caCertFile, String clientCertFile, String privateKeyFile, String password, String tlsVersion, boolean pemFormat) throws CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException, KeyManagementException, FileNotFoundException, InvalidKeySpecException {

    Security.addProvider((Provider)new BouncyCastleProvider());

    X509Certificate caCert = pemFormat ? loadX509CertificatePem(caCertFile) : loadX509Certificate(caCertFile);

    X509Certificate clientCert = pemFormat ? loadX509CertificatePem(clientCertFile) : loadX509Certificate(clientCertFile);

    PrivateKey privateKey = pemFormat ? loadPrivateKeyPem(privateKeyFile, "RSA") : loadPrivateKeyHex(privateKeyFile, "RSA");

    KeyStore caKs = KeyStore.getInstance(KeyStore.getDefaultType());

    caKs.load(null, null);

    caKs.setCertificateEntry("ca-certificate", caCert);

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

    tmf.init(caKs);

    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());

    ks.load(null, null);

    ks.setCertificateEntry("certificate", clientCert);

    ks.setKeyEntry("private-key", privateKey, password.toCharArray(), new Certificate[] { clientCert });

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());

    kmf.init(ks, password.toCharArray());

    SSLContext context = SSLContext.getInstance(tlsVersion);

    context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

    return context.getSocketFactory();

  }

  

  public static SSLSocketFactory createSSLSocketFactory(String trustedKeystoreFile, String trustedCertificateAlias, String trustedKeystorePassword, String clientKeystoreFile, String clientKeystorePassword, String clientKeyPairAlias, String clientKeyPairPassword, String tlsVersion, boolean pemFormat) throws CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException, KeyManagementException, FileNotFoundException, InvalidKeySpecException {

    Security.addProvider((Provider)new BouncyCastleProvider());

    KeyStore caKs = loadKeystore(trustedKeystoreFile, trustedKeystorePassword);

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

    tmf.init(caKs);

    KeyStore ks = loadKeystore(clientKeystoreFile, clientKeystorePassword);

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());

    kmf.init(ks, clientKeyPairPassword.toCharArray());

    SSLContext context = SSLContext.getInstance(tlsVersion);

    context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

    return context.getSocketFactory();

  }

  

  public static SSLSocketFactory createSSLSocketFactory(String tlsVersion) throws NoSuchAlgorithmException, KeyManagementException {

    SSLContext context = SSLContext.getInstance(tlsVersion);

    context.init(null, null, null);

    return context.getSocketFactory();

  }

  

  public static SSLSocketFactory createSSLSocketFactory(String trustedKeystoreFile, String trustedKeystorePassword, String tlsVersion) throws CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException, KeyManagementException, FileNotFoundException, InvalidKeySpecException {

    KeyStore caKs = loadKeystore(trustedKeystoreFile, trustedKeystorePassword);

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

    tmf.init(caKs);

    SSLContext context = SSLContext.getInstance(tlsVersion);

    context.init(null, tmf.getTrustManagers(), null);

    return context.getSocketFactory();

  }

  

  public static SSLSocketFactory createSSLSocketFactory(String caCrtFile, String clientCrtFile, String privateKeyFile, String password, String tlsVersion) throws CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException, KeyManagementException, FileNotFoundException, InvalidKeySpecException {

    return createSSLSocketFactory(caCrtFile, clientCrtFile, privateKeyFile, password, tlsVersion, false);

  }

  

  public static SSLSocketFactory createSSLSocketFactory(String caCrtFile, String tlsVersion) throws KeyManagementException, NoSuchAlgorithmException, IOException, KeyStoreException, CertificateException {

    SSLContext context = SSLContext.getInstance(tlsVersion);

    X509Certificate caCertificate = loadX509Certificate(caCrtFile);

    KeyStore caKs = KeyStore.getInstance(KeyStore.getDefaultType());

    caKs.load(null, null);

    caKs.setCertificateEntry("ca-certificate", caCertificate);

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

    tmf.init(caKs);

    context.init(null, tmf.getTrustManagers(), null);

    return context.getSocketFactory();

  }

  

  public static Certificate loadCertificateFromKeystore(String keyStoreFile, String password, String alias) throws KeyStoreException, IOException, FileNotFoundException, NoSuchAlgorithmException, CertificateException {

    KeyStore keyStore = loadKeystore(keyStoreFile, password);

    Certificate certificate = keyStore.getCertificate(alias);

    return certificate;

  }

  

  public static KeyPair loadKeyPairFromKeystore(String keyStoreFile, String keyStorePassword, String alias, String aliasPassword) throws KeyStoreException, IOException, FileNotFoundException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException {

    KeyPair keyPair = null;

    KeyStore keyStore = loadKeystore(keyStoreFile, keyStorePassword);

    Key key = keyStore.getKey(alias, aliasPassword.toCharArray());

    if (key instanceof PrivateKey) {

      Certificate cert = keyStore.getCertificate(alias);

      PublicKey publicKey = cert.getPublicKey();

      keyPair = new KeyPair(publicKey, (PrivateKey)key);

    } 

    return keyPair;

  }

  

  public static KeyStore loadKeystore(String keyStoreFile, String password) throws FileNotFoundException, KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {

    KeyStore keyStore;

    try (InputStream inStream = new FileInputStream(keyStoreFile)) {

      keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

      keyStore.load(inStream, password.toCharArray());

    } 

    return keyStore;

  }

  

  public static X509Certificate loadX509CertificatePem(String crtFile) throws CertificateException, FileNotFoundException, IOException {

    X509Certificate certificate;

    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    try (InputStream inStream = new FileInputStream(crtFile)) {

      certificate = (X509Certificate)cf.generateCertificate(inStream);

    } 

    return certificate;

  }

  

  public static KeyPair loadKeyPairPem(String publicKeyPemFile, String privateKeyPemFile, String algorithm) throws FileNotFoundException, IOException, NoSuchAlgorithmException, InvalidKeySpecException {

    return new KeyPair(loadPublicKeyPem(publicKeyPemFile, algorithm), loadPrivateKeyPem(privateKeyPemFile, algorithm));

  }

  

  public static PrivateKey loadPrivateKeyPem(String keyPemFile, String algorithm) throws FileNotFoundException, IOException, NoSuchAlgorithmException, InvalidKeySpecException {

    PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(loadPem(keyPemFile));

    PrivateKey privateKey = KeyFactory.getInstance(algorithm).generatePrivate(privateKeySpec);

    return privateKey;

  }

  

  public static PublicKey loadPublicKeyPem(String keyPemFile, String algorithm) throws FileNotFoundException, IOException, NoSuchAlgorithmException, InvalidKeySpecException {

    X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(loadPem(keyPemFile));

    PublicKey publicKey = KeyFactory.getInstance(algorithm).generatePublic(publicKeySpec);

    return publicKey;

  }

  

  public static KeyPair loadKeyPair(String publicKeyFile, String privateKeyFile, String algorithm) throws FileNotFoundException, IOException, NoSuchAlgorithmException, InvalidKeySpecException {

    return new KeyPair(loadPublicKeyHex(publicKeyFile, algorithm), loadPrivateKeyHex(privateKeyFile, algorithm));

  }

  

  public static X509Certificate loadX509Certificate(String crtFile) throws CertificateException, FileNotFoundException, IOException {

    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    InputStream inStream = new FileInputStream(crtFile);

    X509Certificate certificate = (X509Certificate)cf.generateCertificate(inStream);

    inStream.close();

    return certificate;

  }

  

  public static PrivateKey loadPrivateKeyHex(String keyFile, String algorithm) throws FileNotFoundException, IOException, NoSuchAlgorithmException, InvalidKeySpecException {

    PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(loadHex(keyFile));

    PrivateKey privateKey = KeyFactory.getInstance(algorithm).generatePrivate(privateKeySpec);

    return privateKey;

  }

  

  public static PublicKey loadPublicKeyHex(String keyFile, String algorithm) throws FileNotFoundException, IOException, NoSuchAlgorithmException, InvalidKeySpecException {

    X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(loadHex(keyFile));

    PublicKey publicKey = KeyFactory.getInstance(algorithm).generatePublic(publicKeySpec);

    return publicKey;

  }

  

  public static byte[] loadPem(String file) throws FileNotFoundException, IOException {

    PemReader pemReader = new PemReader(new FileReader(file));

    return pemReader.readPemObject().getContent();

  }

  

  public static byte[] loadHex(String file) throws FileNotFoundException, IOException {

    FileInputStream inStream = new FileInputStream(file);

    byte[] encodedData = new byte[inStream.available()];

    inStream.read(encodedData);

    inStream.close();

    return encodedData;

  }

  

  public static void dumpX509Certificate(X509Certificate certificate) {

    if (certificate != null) {

      System.out.println("-----[X509Certificate]-----");

      System.out.println("Subject DN: " + certificate.getSubjectDN());

      System.out.println("Type: " + certificate.getType());

      System.out.println("Version: " + certificate.getVersion());

      System.out.println("Serial Number:" + certificate.getSerialNumber());

      System.out.println("Valid From: " + certificate.getNotBefore());

      System.out.println("Valid To: " + certificate.getNotAfter());

      System.out.println("-----[END]");

    } 

  }

  

  public static void dumpKeyPair(KeyPair keyPair) {

    if (keyPair != null) {

      PublicKey publicKey = keyPair.getPublic();

      PrivateKey privateKey = keyPair.getPrivate();

      dumpHexKey("Public Key", publicKey);

      dumpHexKey("Private Key", privateKey);

    } 

  }

  

  public static void dumpHexKey(String label, Key key) {

    System.out.println("-----[" + label + "]-----");

    System.out.println(encodeAsString(key.getEncoded()));

    System.out.println("-----[END]");

  }

  

  public static String encodeAsString(byte[] b) {

    String result = "";

    for (int i = 0; i < b.length; i++)

      result = result + Integer.toString((b[i] & 0xFF) + 256, 16).substring(1); 

    return result;

  }

}