Creating certificates for SSL communication

后端 未结 1 1137
执念已碎
执念已碎 2021-01-18 14:37

I am working on a distributed application with a number of uniquely identified slave processes that will communicate with a master application via SSL enabled sockets. The a

相关标签:
1条回答
  • 2021-01-18 14:50

    From a technical point of view your solution is correct. However do not forget the security considerations: who can request a certificate, how the authentication is performed, how the certificates/private keys are distributed to the servers...

    These elements are mandatory for a certificate generation:

    • Subject Name
    • Issuer name
    • certificate serial number
    • subject public key
    • validity dates (not before, not after)

    It is also a good practice to add some extensions:

    • Subject Key Identifier
    • Authority Key Indentifier
    • Basic Constraints
    • Key Usage
    • Extended Key Usages

    This code snippet outlines the certificate generation:

    ContentSigner getCertSigner(PrivateKey issuerKey) {
      AsymmetricKeyParameter akp = PrivateKeyFactory.createKey(issuerKey.getEncoded());
      AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withRSA");
      AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
      return new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(akp);
    }
    
    X509CertificateHolder generateCertificate(X509Certificate issuerCert, PrivateKey issuerKey, X500Name subject, PublicKey subjectKey, Date notBefore, Date notAfter) {
      X509Principal issuerDN = PrincipalUtil.getSubjectX509Principal(issuerCert);
      SubjectPublicKeyInfo key = SubjectPublicKeyInfo.getInstance(subjectKey.getEncoded());
      X509v3CertificateBuilder builder = new X509v3CertificateBuilder(issuerDN, BigInteger.valueOf(new SecureRandom().nextInt()), before, after, subject, key);
    
      // Add authority key identifier
      builder.addExtension(X509Extension.authorityKeyIdentifier, false, JcaX509ExtensionUtils.createAuthorityKeyIdentifier(issuerCert));
    
      // Add subject key identifier
      builder.addExtension(X509Extension.subjectKeyIdentifier, false, JcaX509ExtensionUtils.createSubjectKeyIdentifier(subjectKey));
    
      // Add basic constraints
      builder.addExtension(X509Extension.basicConstraints, true, new BasicConstraints(false));
    
      // Add key usage
      KeyUsage keyUsage = new KeyUsage(KeyUsage.keyEncipherment|KeyUsage.digitalSignature);
      builder.addExtension(X509Extension.keyUsage, true, keyUsage);
    
      // Add extended key usage
      ExtendedKeyUsage extKeyUsage = new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth);
      builder.addExtension(X509Extension.extendedKeyUsage, false, extKeyUsage);
    
      return builder.build(getCertSigner(issuerKey));
    }
    

    UPDATE: fixed the code according to Martin Nielsen's comment.

    0 讨论(0)
提交回复
热议问题