/** * @return sha-256 string based on cert in keystore */ public static String getCertFingerPrint(String storePath, String alias,String pass) { try { Certificate cert = DTLSUtils.loadCert(storePath, alias, pass); byte[] der = cert.getCertificateAt(0).getEncoded(); MessageDigest md = MessageDigest.getInstance("SHA-256"); byte[] dat = md.digest(der); String fingerprint = createFingerprintString(dat); logger.info("Local cert signature is {} ",fingerprint); return fingerprint; } catch (Exception e) { logger.error("Failed to create cert fingerprint from {}",storePath ,e); throw new IllegalStateException("Loading certificate failed"); } }
public static void main(String[] args) throws IOException, CertificateException, NoSuchProviderException { Security.addProvider(new BouncyCastleProvider()); final X509Certificate clientCertX509 = CertificateClientManagement.loadCertificate("secure/cert/test.crt"); final Certificate clientCert = new Certificate(new org.bouncycastle.asn1.x509.Certificate[] {org.bouncycastle.asn1.x509.Certificate.getInstance(clientCertX509.getEncoded())}); final KeyPair clientKeyPair = CertificateClientManagement.loadKey("secure/cert/test.key", clientCertX509.getPublicKey()); Socket socket = new Socket("localhost", 4444); TlsClientProtocol tlsClientProtocol = new CustomTlsClientProtocol(socket.getInputStream(), socket.getOutputStream()); tlsClientProtocol.connect(new CustomTlsClient(clientKeyPair, clientCert)); System.out.println("auth finished"); while (true); }
static String fingerprint(org.bouncycastle.asn1.x509.Certificate c) throws IOException { byte[] der = c.getEncoded(); byte[] sha1 = sha256DigestOf(der); byte[] hexBytes = Hex.encode(sha1); String hex = new String(hexBytes, "ASCII").toUpperCase(); StringBuffer fp = new StringBuffer(); int i = 0; fp.append(hex.substring(i, i + 2)); while ((i += 2) < hex.length()) { fp.append(':'); fp.append(hex.substring(i, i + 2)); } return fp.toString(); }
static DTLSTransport createServerTransport(final RTCCertificate rtcCertificate, final DatagramTransport transport) throws IOException { final DefaultTlsServer defaultTlsServer = new DefaultTlsServer() { private final AsymmetricKeyParameter privateKeyAsymKeyParam = PrivateKeyFactory.createKey(rtcCertificate.getKeyPair() .getPrivate() .getEncoded()); private final Certificate cCert = new Certificate(new org.bouncycastle.asn1.x509.Certificate[]{rtcCertificate.getCertificate().toASN1Structure()}); @Override protected ProtocolVersion getMaximumVersion() { return ProtocolVersion.DTLSv10; } @Override protected ProtocolVersion getMinimumVersion() { return ProtocolVersion.DTLSv10; } @Override protected TlsSignerCredentials getRSASignerCredentials() throws IOException { return new DefaultTlsSignerCredentials(this.context, this.cCert, this.privateKeyAsymKeyParam); } }; return new DTLSServerProtocol(SECURE_RANDOM).accept(defaultTlsServer, transport); }
static DTLSTransport createClientTransport(final DatagramTransport transport) throws IOException { final DefaultTlsClient defaultTlsClient = new DefaultTlsClient() { @Override public ProtocolVersion getClientVersion() { return ProtocolVersion.DTLSv10; } @Override public ProtocolVersion getMinimumVersion() { return ProtocolVersion.DTLSv10; } @Override public TlsAuthentication getAuthentication() throws IOException { return new ServerOnlyTlsAuthentication() { @Override public void notifyServerCertificate(final Certificate serverCertificate) throws IOException { //TODO Check if certificate is signed by a trusted party. } }; } }; return new DTLSClientProtocol(SECURE_RANDOM).connect(defaultTlsClient, transport); }
@Override public Certificate unmarshal(String v) throws Exception { Certificate cert = Certificate.parse(new ByteArrayInputStream(ArrayConverter.hexStringToByteArray(v.replaceAll( "\\s+", "")))); return cert; }
@Override public void adjustTLSContext(CertificateMessage message) { Certificate cert; if (tlsContext.getChooser().getSelectedProtocolVersion().isTLS13()) { ByteArrayOutputStream stream = new ByteArrayOutputStream(); int certificatesLength = 0; try { for (CertificatePair pair : message.getCertificatesList()) { stream.write(ArrayConverter.intToBytes(pair.getCertificateLength().getValue(), HandshakeByteLength.CERTIFICATE_LENGTH)); stream.write(pair.getCertificate().getValue()); certificatesLength += pair.getCertificateLength().getValue() + HandshakeByteLength.CERTIFICATE_LENGTH; } } catch (IOException ex) { throw new AdjustmentException("Could not concatenate certificates bytes", ex); } cert = parseCertificate(certificatesLength, stream.toByteArray()); } else { cert = parseCertificate(message.getCertificatesListLength().getValue(), message.getCertificatesListBytes() .getValue()); } if (tlsContext.getTalkingConnectionEndType() == ConnectionEndType.CLIENT) { LOGGER.debug("Setting ClientCertificate in Context"); tlsContext.setClientCertificate(cert); } else { LOGGER.debug("Setting ServerCertificate in Context"); tlsContext.setServerCertificate(cert); } if (cert != null) { adjustPublicKeyParameters(cert); } if (tlsContext.getChooser().getSelectedProtocolVersion().isTLS13()) { adjustExtensions(message); } }
private void adjustPublicKeyParameters(Certificate cert) { try { if (CertificateUtils.hasDHParameters(cert)) { LOGGER.debug("Adjusting DH PublicKey"); DHPublicKeyParameters dhParameters = CertificateUtils.extractDHPublicKeyParameters(cert); adjustDHParameters(dhParameters); } else if (CertificateUtils.hasECParameters(cert)) { LOGGER.debug("Adjusting EC PublicKey"); ECPublicKeyParameters ecParameters = CertificateUtils.extractECPublicKeyParameters(cert); adjustECParameters(ecParameters); } else if (CertificateUtils.hasRSAParameters(cert)) { LOGGER.debug("Adjusting RSA PublicKey"); if (tlsContext.getTalkingConnectionEndType() == ConnectionEndType.CLIENT) { tlsContext.setClientRSAPublicKey(CertificateUtils.extractRSAPublicKey(cert)); tlsContext.setClientRSAPrivateKey(tlsContext.getConfig().getDefaultClientRSAPrivateKey()); tlsContext.setClientRsaModulus(CertificateUtils.extractRSAModulus(cert)); } else { tlsContext.setServerRSAPublicKey(CertificateUtils.extractRSAPublicKey(cert)); tlsContext.setServerRSAPrivateKey(tlsContext.getConfig().getDefaultServerRSAPrivateKey()); tlsContext.setServerRsaModulus(CertificateUtils.extractRSAModulus(cert)); } } else { LOGGER.warn("Could not adjust Certificate publicKey"); } } catch (IOException E) { throw new AdjustmentException("Could not adjust PublicKey Information from Certificate", E); } }
private Certificate parseCertificate(int lengthBytes, byte[] bytesToParse) { try { ByteArrayInputStream stream = new ByteArrayInputStream(ArrayConverter.concatenate( ArrayConverter.intToBytes(lengthBytes, HandshakeByteLength.CERTIFICATES_LENGTH), bytesToParse)); return Certificate.parse(stream); } catch (IOException | IllegalArgumentException E) { LOGGER.warn("Could not parse Certificate bytes into Certificate object:" + ArrayConverter.bytesToHexString(bytesToParse, false)); LOGGER.debug(E); return null; } }
public static Certificate fetchServerCertificate(Config config) { State state = new State(config); config.setWorkflowTraceType(WorkflowTraceType.HELLO); WorkflowExecutor workflowExecutor = WorkflowExecutorFactory.createWorkflowExecutor( WorkflowExecutorType.DEFAULT, state); try { workflowExecutor.executeWorkflow(); } catch (WorkflowExecutionException E) { LOGGER.warn("Could not fetch ServerCertificate"); LOGGER.debug(E); } return state.getTlsContext().getServerCertificate(); }
/** * Parses the leaf Certificate PublicKey from the CertificateStructure * * @param cert * The Certificate from which the PublicKey should be extracted * @return The parsed PublicKey */ public static PublicKey parsePublicKey(Certificate cert) { try { X509CertificateObject certObj = new X509CertificateObject(cert.getCertificateAt(0)); return certObj.getPublicKey(); } catch (CertificateParsingException | IllegalArgumentException | ClassCastException ex) { LOGGER.warn("Could not extract public key from Certificate!"); LOGGER.debug(ex); return null; } }
public static boolean hasDHParameters(Certificate cert) { if (cert.isEmpty()) { return false; } SubjectPublicKeyInfo keyInfo = cert.getCertificateAt(0).getSubjectPublicKeyInfo(); return keyInfo.getAlgorithm().getAlgorithm().equals(X9ObjectIdentifiers.dhpublicnumber); }
public static boolean hasECParameters(Certificate cert) { if (cert.isEmpty()) { return false; } SubjectPublicKeyInfo keyInfo = cert.getCertificateAt(0).getSubjectPublicKeyInfo(); return keyInfo.getAlgorithm().getAlgorithm().equals(X9ObjectIdentifiers.id_ecPublicKey); }
public static boolean hasRSAParameters(Certificate cert) { if (cert.isEmpty()) { return false; } PublicKey key = parsePublicKey(cert); return key != null && key instanceof RSAPublicKey; }
public static DHPublicKeyParameters extractDHPublicKeyParameters(Certificate cert) throws IOException { if (hasDHParameters(cert)) { SubjectPublicKeyInfo keyInfo = cert.getCertificateAt(0).getSubjectPublicKeyInfo(); return (DHPublicKeyParameters) PublicKeyFactory.createKey(keyInfo); } else { throw new IOException(); } }
public static ECPublicKeyParameters extractECPublicKeyParameters(Certificate cert) throws IOException { if (hasECParameters(cert)) { SubjectPublicKeyInfo keyInfo = cert.getCertificateAt(0).getSubjectPublicKeyInfo(); return (ECPublicKeyParameters) PublicKeyFactory.createKey(keyInfo); } else { throw new IOException(); } }
public static BigInteger extractRSAModulus(Certificate cert) throws IOException { if (hasRSAParameters(cert)) { RSAPublicKey rsaPubKey = (RSAPublicKey) parsePublicKey(cert); return rsaPubKey.getModulus(); } else { throw new IOException(); } }
public static BigInteger extractRSAPublicKey(Certificate cert) throws IOException { if (hasRSAParameters(cert)) { RSAPublicKey rsaPubKey = (RSAPublicKey) parsePublicKey(cert); return rsaPubKey.getPublicExponent(); } else { throw new IOException(); } }
public static Certificate getTestCertificate() { try { ByteArrayInputStream bin = new ByteArrayInputStream(cert1); ASN1InputStream ain = new ASN1InputStream(bin); Certificate obj = Certificate.parse(ain); return obj; } catch (IOException ex) { ex.printStackTrace(); } return null; }
public static KeyPair keyPairFromStore(KeyStore keyStore, String keyAlias, String keyPass) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException { PrivateKey privKey = (PrivateKey) keyStore.getKey(keyAlias, keyPass.toCharArray()); java.security.cert.Certificate cert = keyStore.getCertificate(keyAlias); PublicKey pubKey = cert.getPublicKey(); return new KeyPair(pubKey, privKey); }
private Certificate parseCertificate(int lengthBytes, byte[] bytesToParse) { try { ByteArrayInputStream stream = new ByteArrayInputStream(ArrayConverter.concatenate( ArrayConverter.intToBytes(lengthBytes, HandshakeByteLength.CERTIFICATES_LENGTH), bytesToParse)); return Certificate.parse(stream); } catch (IOException E) { LOGGER.warn("Could not parse Certificate bytes into Certificate object:" + ArrayConverter.bytesToHexString(bytesToParse, false)); return null; } }
@Test public void testPrepareSSL3() throws IOException { CertificateMessage certmessage = new CertificateMessage(); certmessage .setCertificatesListBytes(ArrayConverter .hexStringToByteArray("00027a30820276308201dfa003020102020438918374300d06092a864886f70d01010b0500306e3110300e06035504061307556e6b6e6f776e3110300e06035504081307556e6b6e6f776e3110300e06035504071307556e6b6e6f776e3110300e060355040a1307556e6b6e6f776e3110300e060355040b1307556e6b6e6f776e3112301006035504031309616e6f6e796d6f7573301e170d3135303830343133353731375a170d3235303830313133353731375a306e3110300e06035504061307556e6b6e6f776e3110300e06035504081307556e6b6e6f776e3110300e06035504071307556e6b6e6f776e3110300e060355040a1307556e6b6e6f776e3110300e060355040b1307556e6b6e6f776e3112301006035504031309616e6f6e796d6f757330819f300d06092a864886f70d010101050003818d00308189028181008a4ee023df569ce17c504cbb828f16bae5040ccef4b59ef96733dfe34693530d4062f9b4873c72f933607f8ceea01ad2215dab44eaac207f45de5835a8db4e21b35d5e2757f652eaaa25d71a60c37725cddf877427cc9e60e240d0429e708bc4b6017726734b2c03f404d5fea407d91bbe4e86a0ebc685e8078f8657b5830ab30203010001a321301f301d0603551d0e04160414611782c41da8bd62a49ce58580194baa5d8c764f300d06092a864886f70d01010b0500038181005f9708702b8adb185b2db0d05845af5df1f7d13e7a94647a8653187e7a55753f5c19772a994f53136ab04cdad266683bf65a1b78fca418899e44c0e8f75add9df5b432e92a6a0668b16d6278a67c78f8ea30ca587e1dc314d8312d41808284e22df19c7f4bb3086e74b42c9473df8b82449643a4e2fbb05cf8b1b41acec44fe9")); certmessage.setCertificatesListLength(637); Security.addProvider(new BouncyCastleProvider()); CertificateHandler handler = new CertificateHandler(context); handler.adjustTLSContext(certmessage); Certificate cert = parseCertificate(certmessage.getCertificatesListLength().getValue(), certmessage .getCertificatesListBytes().getValue()); context.setClientRsaModulus(CertificateUtils.extractRSAModulus(cert)); String preMasterSecret = "1a4dc552ddd7e1e25dbaff38dd447b3a6fdc85120e2f760fefdab88e5adbbc710f3d0843f07c9f4f5ac01bc4cea02c4030c272074aa04b1b80a71123b73ea4efbe928b54a83fe4b39472bf66a953c7dc11cfb13ea08f92047996799ce702eb72a7c69bdfd98b91a09bcb836414752d93d3641740f8ed5cfff682225434052230"; String keyEx = " 100000801a4dc552ddd7e1e25dbaff38dd447b3a6fdc85120e2f760fefdab88e5adbbc710f3d0843f07c9f4f5ac01bc4cea02c4030c272074aa04b1b80a71123b73ea4efbe928b54a83fe4b39472bf66a953c7dc11cfb13ea08f92047996799ce702eb72a7c69bdfd98b91a09bcb836414752d93d3641740f8ed5cfff682225434052230"; System.err.println(keyEx.length()); context.setSelectedCipherSuite(CipherSuite.TLS_RSA_WITH_NULL_MD5); context.setSelectedProtocolVersion(ProtocolVersion.SSL3); context.setClientRandom(ArrayConverter .hexStringToByteArray("405e2a60cefcb557edd6d41336a3fa4b2dfdae20f4ac7adacbb29c13456e2800")); System.err.println("405e2a60cefcb557edd6d41336a3fa4b2dfdae20f4ac7adacbb29c13456e2800".length()); context.setServerRandom(ArrayConverter .hexStringToByteArray("a63cd22a46e4fc22b1f03d579c5f0e43cadfda01ef615fd52a9cdbaed3f6c6c2")); System.err.println(context.getChooser().getServerRsaModulus().bitLength()); // context.setRsaModulus(CertificateUtils.extractRSAModulus(cert)); // Test preparator.prepareHandshakeMessageContents(); LOGGER.info(ArrayConverter.bytesToHexString(message.getComputations().getPlainPaddedPremasterSecret(), false)); }
@Test public void testDefaultCertificates() throws IOException { Config config = Config.createConfig(); Certificate cert = Certificate.parse(new ByteArrayInputStream(config.getDefaultRsaCertificate())); cert = Certificate.parse(new ByteArrayInputStream(config.getDefaultEcCertificate())); cert = Certificate.parse(new ByteArrayInputStream(config.getDefaultDsaCertificate())); }
private void checkConnectionClient(TlsClient client, int cipherSuite, byte[] encCert) throws Exception { client.notifySelectedCipherSuite(cipherSuite); TlsKeyExchange keyExchange = client.getKeyExchange(); keyExchange .processServerCertificate(new Certificate( new org.bouncycastle.asn1.x509.Certificate[]{org.bouncycastle.asn1.x509.Certificate .getInstance(encCert)})); }
static TlsAgreementCredentials loadAgreementCredentials(TlsContext context, String[] certResources, String keyResource) throws IOException { Certificate certificate = loadCertificateChain(certResources); AsymmetricKeyParameter privateKey = loadPrivateKeyResource(keyResource); return new DefaultTlsAgreementCredentials(certificate, privateKey); }
static TlsEncryptionCredentials loadEncryptionCredentials(TlsContext context, String[] certResources, String keyResource) throws IOException { Certificate certificate = loadCertificateChain(certResources); AsymmetricKeyParameter privateKey = loadPrivateKeyResource(keyResource); return new DefaultTlsEncryptionCredentials(context, certificate, privateKey); }
static TlsSignerCredentials loadSignerCredentials(TlsContext context, String[] certResources, String keyResource) throws IOException { Certificate certificate = loadCertificateChain(certResources); AsymmetricKeyParameter privateKey = loadPrivateKeyResource(keyResource); return new DefaultTlsSignerCredentials(context, certificate, privateKey); }
static Certificate loadCertificateChain(String[] resources) throws IOException { org.bouncycastle.asn1.x509.Certificate[] chain = new org.bouncycastle.asn1.x509.Certificate[resources.length]; for (int i = 0; i < resources.length; ++i) { chain[i] = loadCertificateResource(resources[i]); } return new Certificate(chain); }
static org.bouncycastle.asn1.x509.Certificate loadCertificateResource(String resource) throws IOException { PemObject pem = loadPemResource(resource); if (pem.getType().endsWith("CERTIFICATE")) { return org.bouncycastle.asn1.x509.Certificate.getInstance(pem.getContent()); } throw new IllegalArgumentException("'resource' doesn't specify a valid certificate"); }
@Override public String marshal(Certificate v) throws Exception { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); v.encode(outStream); return ArrayConverter.bytesToHexString(outStream.toByteArray()); }
private Certificate getCertificate(Config config) throws IOException { return Certificate.parse(new ByteArrayInputStream(CertificateByteChooser.chooseCertificateType(config))); }
public Certificate getServerCertificate() { return serverCertificate; }
public void setServerCertificate(Certificate serverCertificate) { this.serverCertificate = serverCertificate; }