美文网首页服务器学习程序员Android知识
Android 上SSL Socket双向认证加密通信

Android 上SSL Socket双向认证加密通信

作者: genylife | 来源:发表于2017-03-29 15:57 被阅读355次

    作者Blog(http://genylife.top/)


    密钥制作(命名解释:k -> keymanager ; t -> TrustManager)

    • 通过Java 的keytool 工具生成密钥

      keytool -genkey -v -alias server -keyalg RSA -storetype PKCS12 -keystore kserver.p12
      

      NOTICE:

      1. 指定别名为server
      2. 指定存储类型为PKCS12
      3. 指定文件名kserver.p12
    • 导出所生成的密钥证书

      keytool -export -alias server -keystore kserver.p12 -storetype PKCS12 -file server.cer
      

      NOTICE:

      1. 指定别名为上一步所设置的别名
      2. 指定密钥文件为上一步生成的文件名
      3. 存储类型匹配PKCS12
      4. 制定文件名server.cer
    • 将证书导出为Android 支持的BKS 格式

      keytool -importcert -v -trustcacerts -alias server -file server.cer -keystore tclient.bks -storetype BKS -providerclass org.bouncycastle.jce.provider.BouncyCastleProvider -providerpath bcprov-jdk15on-146.jar
      

      NOTICE:

      1. 指定证书文件server.cer
      2. 指定生成的BKS格式文件tclient.bks
      3. 指定存储类型BKS
      4. 需要下载文件bcprov-jdk15on-146.jar ,并设置其路径,路径指定为providerpath
      5. 设置转换的providerclass
    • 至此,服务器端的密钥和客户端的证书就制作完成了,然后再制作客户端的密钥和服务器端的证书

      keytool -genkey -v -alias clent -keyalg RSA -storetype PKCS12 -keystore kclient.p12
      
      keytool -export -alias client -keystore kclient.p12 -storetype PKCS12 -file client.cer
      
      keytool -importcert -v -trustcacerts -alias server -file client.cer -keystore tserver.bks -storetype BKS -providerclass org.bouncycastle.jce.provider.BouncyCastleProvider -providerpath bcprov-jdk15on-146.jar
      
    • kserver.p12tserver.bks 放在服务器端,把kclient.p12tclient.bks 放在客户端

    创建KeyManagers

    public class AliasKeyManager implements X509KeyManager {
    
            private KeyStore _ks;
            private String _alias;
            private String _password;
    
            public AliasKeyManager(KeyStore ks, String alias, String password) {
                _ks = ks;
                _alias = alias;
                _password = password;
            }
    
            public String chooseClientAlias(String[] str, Principal[] principal, Socket socket) {
                return _alias;
            }
    
            public String chooseServerAlias(String str, Principal[] principal, Socket socket) {
                return _alias;
            }
    
            public X509Certificate[] getCertificateChain(String alias) {
                try {
                    java.security.cert.Certificate[] certificates = this._ks.getCertificateChain(alias);
                    if(certificates == null) {
                        throw new FileNotFoundException("no certificate found for alias:" + alias);
                    }
                    X509Certificate[] x509Certificates = new X509Certificate[certificates.length];
                    System.arraycopy(certificates, 0, x509Certificates, 0, certificates.length);
                    return x509Certificates;
                } catch (Exception e) {
                    e.printStackTrace();
                    return null;
                }
            }
    
            public String[] getClientAliases(String str, Principal[] principal) {
                return new String[]{_alias};
            }
    
            public PrivateKey getPrivateKey(String alias) {
                try {
                    return (PrivateKey) _ks.getKey(alias, _password == null ? null : _password.toCharArray());
                } catch (Exception e) {
                    e.printStackTrace();
                    return null;
                }
            }
    
            public String[] getServerAliases(String str, Principal[] principal) {
                return new String[]{_alias};
            }
        }
    
    KeyManager[] createKeyManagers(String keyStoreFileName, String keyStorePassword, String alias)
                throws CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
            final String KEY_STORE_TYPE_P12 = "PKCS12";
            InputStream inputStream = pContext.getResources().getAssets().open(keyStoreFileName);
            KeyStore keyStore = KeyStore.getInstance(KEY_STORE_TYPE_P12);
            keyStore.load(inputStream, keyStorePassword.toCharArray());
    
            KeyManager[] managers;
            if(alias != null) {
                managers = new KeyManager[]{new AliasKeyManager(keyStore, alias, keyStorePassword)};
            } else {
                KeyManagerFactory keyManagerFactory =
                        KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
                keyManagerFactory.init(keyStore, keyStorePassword == null ? null : keyStorePassword.toCharArray());
                managers = keyManagerFactory.getKeyManagers();
            }
            return managers;
    

    创建TrustManagers

    TrustManager[] createTrustManagers(String trustStoreFileName, String trustStorePassword)
                throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
            final String KEY_STORE_TYPE_BKS = "bks";
            InputStream inputStream = pContext.getResources().getAssets().open(trustStoreFileName);
            KeyStore trustStore = KeyStore.getInstance(KEY_STORE_TYPE_BKS);
            trustStore.load(inputStream, trustStorePassword.toCharArray());
    
            TrustManagerFactory trustManagerFactory =
                    TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(trustStore);
            return trustManagerFactory.getTrustManagers();
        }
    

    创建SocketFactory

     SSLContext context = SSLContext.getInstance("TLS");
     KeyManager[] keyManagers = createKeyManagers(keyStoreFileName, keyStorePassword, alias);
     TrustManager[] trustManagers = createTrustManagers(trustStoreFileName, trustStorePassword);
     context.init(keyManagers, trustManagers, null);
    
     //  获取SSLServerSocketFactory
     SSLServerSocketFactory socketFactory = context.getServerSocketFactory();
    
     //  获取SSLSocketFactory
     SSLSocketFactory socketFactory = context.getSocketFactory();
    

    作者Blog(http://genylife.top/)

    相关文章

      网友评论

        本文标题:Android 上SSL Socket双向认证加密通信

        本文链接:https://www.haomeiwen.com/subject/sltyottx.html