Search in sources :

Example 6 with X500NameBuilder

use of org.spongycastle.asn1.x500.X500NameBuilder in project kdeconnect-android by KDE.

the class DeviceTest method testPairingDoneWithCertificate.

public void testPairingDoneWithCertificate() throws Exception {
    KeyPair keyPair = null;
    try {
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(2048);
        keyPair = keyGen.genKeyPair();
    } catch (Exception e) {
        e.printStackTrace();
        Log.e("KDE/initializeRsaKeys", "Exception");
    }
    X509Certificate certificate = null;
    try {
        BouncyCastleProvider BC = new BouncyCastleProvider();
        X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
        nameBuilder.addRDN(BCStyle.CN, "testDevice");
        nameBuilder.addRDN(BCStyle.OU, "KDE Connect");
        nameBuilder.addRDN(BCStyle.O, "KDE");
        Date notBefore = new Date(System.currentTimeMillis());
        Date notAfter = new Date(System.currentTimeMillis() + System.currentTimeMillis());
        X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(nameBuilder.build(), BigInteger.ONE, notBefore, notAfter, nameBuilder.build(), keyPair.getPublic());
        ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider(BC).build(keyPair.getPrivate());
        certificate = new JcaX509CertificateConverter().setProvider(BC).getCertificate(certificateBuilder.build(contentSigner));
    } catch (Exception e) {
        e.printStackTrace();
        Log.e("KDE/initialiseCert", "Exception");
    }
    NetworkPackage fakeNetworkPackage = new NetworkPackage(NetworkPackage.PACKAGE_TYPE_IDENTITY);
    fakeNetworkPackage.set("deviceId", "unpairedTestDevice");
    fakeNetworkPackage.set("deviceName", "Unpaired Test Device");
    fakeNetworkPackage.set("protocolVersion", NetworkPackage.ProtocolVersion);
    fakeNetworkPackage.set("deviceType", Device.DeviceType.Phone.toString());
    fakeNetworkPackage.set("certificate", Base64.encodeToString(certificate.getEncoded(), 0));
    LanLinkProvider linkProvider = Mockito.mock(LanLinkProvider.class);
    Mockito.when(linkProvider.getName()).thenReturn("LanLinkProvider");
    LanLink link = Mockito.mock(LanLink.class);
    Mockito.when(link.getPairingHandler(Mockito.any(Device.class), Mockito.any(BasePairingHandler.PairingHandlerCallback.class))).thenReturn(Mockito.mock(LanPairingHandler.class));
    Mockito.when(link.getLinkProvider()).thenReturn(linkProvider);
    Device device = new Device(getContext(), fakeNetworkPackage, link);
    device.publicKey = keyPair.getPublic();
    assertNotNull(device);
    assertEquals(device.getDeviceId(), "unpairedTestDevice");
    assertEquals(device.getName(), "Unpaired Test Device");
    assertEquals(device.getDeviceType(), Device.DeviceType.Phone);
    assertNotNull(device.publicKey);
    assertNotNull(device.certificate);
    Method method;
    try {
        method = Device.class.getDeclaredMethod("pairingDone");
        method.setAccessible(true);
        method.invoke(device);
    } catch (Exception e) {
        e.printStackTrace();
    }
    assertEquals(device.isPaired(), true);
    SharedPreferences preferences = getContext().getSharedPreferences("trusted_devices", Context.MODE_PRIVATE);
    assertEquals(preferences.getBoolean(device.getDeviceId(), false), true);
    SharedPreferences settings = getContext().getSharedPreferences(device.getDeviceId(), Context.MODE_PRIVATE);
    assertEquals(settings.getString("deviceName", "Unknown device"), "Unpaired Test Device");
    assertEquals(settings.getString("deviceType", "tablet"), "phone");
    // Cleanup for unpaired test device
    preferences.edit().remove(device.getDeviceId()).apply();
    settings.edit().clear().apply();
}
Also used : KeyPair(java.security.KeyPair) LanLink(org.kde.kdeconnect.Backends.LanBackend.LanLink) X500NameBuilder(org.spongycastle.asn1.x500.X500NameBuilder) SharedPreferences(android.content.SharedPreferences) JcaContentSignerBuilder(org.spongycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.spongycastle.operator.ContentSigner) KeyPairGenerator(java.security.KeyPairGenerator) Method(java.lang.reflect.Method) X509Certificate(java.security.cert.X509Certificate) Date(java.util.Date) LanLinkProvider(org.kde.kdeconnect.Backends.LanBackend.LanLinkProvider) JcaX509v3CertificateBuilder(org.spongycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.spongycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.spongycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.spongycastle.cert.jcajce.JcaX509v3CertificateBuilder) LanPairingHandler(org.kde.kdeconnect.Backends.LanBackend.LanPairingHandler) BouncyCastleProvider(org.spongycastle.jce.provider.BouncyCastleProvider)

Example 7 with X500NameBuilder

use of org.spongycastle.asn1.x500.X500NameBuilder in project ddf by codice.

the class PkiTools method convertDistinguishedName.

public static X500Name convertDistinguishedName(String... tuples) {
    Validate.isTrue(tuples != null && tuples.length > 0, "Distinguished name must consist of at least one component");
    assert tuples != null && tuples.length > 0;
    Pattern tuplePattern = Pattern.compile(".*[=].*");
    Validate.isTrue(Arrays.stream(tuples).allMatch(t -> tuplePattern.matcher(t).matches()), "Distinguished name components must be in the format symbol=value");
    AttributeNameChecker style = new AttributeNameChecker();
    Validate.isTrue(Arrays.stream(tuples).map(t -> t.split("[=]")[0]).map(String::trim).allMatch(style::isValidName));
    X500NameBuilder nameBuilder = new X500NameBuilder(RFC4519Style.INSTANCE);
    Arrays.stream(tuples).map(t -> t.split("[=]")).forEach(t -> nameBuilder.addRDN(style.lookupByName(t[0].trim()), t[1].trim()));
    return nameBuilder.build();
}
Also used : X509Certificate(java.security.cert.X509Certificate) KeyPair(java.security.KeyPair) Arrays(java.util.Arrays) CertificateFactory(org.bouncycastle.jcajce.provider.asymmetric.x509.CertificateFactory) LoggerFactory(org.slf4j.LoggerFactory) InetAddress(java.net.InetAddress) X500Name(org.bouncycastle.asn1.x500.X500Name) GeneralSecurityException(java.security.GeneralSecurityException) ByteArrayInputStream(java.io.ByteArrayInputStream) RFC4519Style(org.bouncycastle.asn1.x500.style.RFC4519Style) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) X500NameBuilder(org.bouncycastle.asn1.x500.X500NameBuilder) KeyPairGenerator(java.security.KeyPairGenerator) Logger(org.slf4j.Logger) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) UnknownHostException(java.net.UnknownHostException) File(java.io.File) FileNotFoundException(java.io.FileNotFoundException) KeyFactory(java.security.KeyFactory) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) Key(java.security.Key) Base64(java.util.Base64) PrivateKey(java.security.PrivateKey) Pattern(java.util.regex.Pattern) Validate(org.apache.commons.lang.Validate) CertificateEncodingException(java.security.cert.CertificateEncodingException) Pattern(java.util.regex.Pattern) X500NameBuilder(org.bouncycastle.asn1.x500.X500NameBuilder)

Example 8 with X500NameBuilder

use of org.spongycastle.asn1.x500.X500NameBuilder in project ddf by codice.

the class PkiTools method makeDistinguishedName.

/**
     * Create an X500 name with a single populated attribute, the "common name". An X500 name object details the
     * identity of a machine, person, or organization. The name object is used as the "subject" of a certificate.
     * SSL/TLS typically uses a subject's common name as the DNS name for a machine and this name must be correct
     * or SSl/TLS will not trust the machine's certificate.
     * <p>
     * TLS can use a different set of attributes to, the Subject Alternative Names. SANs are extensions to the
     * X509 specification and can include IP addresses, DNS names and other machine information. This package does
     * not use SANs.
     *
     * @param commonName the fully qualified host name of the end entity
     * @return X500 name object with common name attribute set
     * @see <a href="https://www.ietf.org/rfc/rfc4514.txt">RFC 4514, section 'LDAP: Distinguished Names'</a>
     * @see <a href="https://tools.ietf.org/html/rfc4519">RFC 4519 details the exact construction of distinguished names</a>
     * @see <a href="https://en.wikipedia.org/wiki/SubjectAltName">Subject Alternative Names on Wikipedia'</a>
     */
public static X500Name makeDistinguishedName(String commonName) {
    Validate.isTrue(commonName != null, "Certificate common name cannot be null");
    assert commonName != null;
    if (commonName.isEmpty()) {
        LOGGER.warn("Setting certificate common name to empty string. This could result in an unusable TLS certificate.");
    }
    X500NameBuilder nameBuilder = new X500NameBuilder(RFC4519Style.INSTANCE);
    //Add more nameBuilder.addRDN(....) statements to support more X500 attributes.
    nameBuilder.addRDN(RFC4519Style.cn, commonName);
    return nameBuilder.build();
}
Also used : X500NameBuilder(org.bouncycastle.asn1.x500.X500NameBuilder)

Example 9 with X500NameBuilder

use of org.spongycastle.asn1.x500.X500NameBuilder in project gitblit by gitblit.

the class X509Utils method buildDistinguishedName.

/**
	 * Builds a distinguished name from the X509Metadata.
	 *
	 * @return a DN
	 */
private static X500Name buildDistinguishedName(X509Metadata metadata) {
    X500NameBuilder dnBuilder = new X500NameBuilder(BCStyle.INSTANCE);
    setOID(dnBuilder, metadata, "C", null);
    setOID(dnBuilder, metadata, "ST", null);
    setOID(dnBuilder, metadata, "L", null);
    setOID(dnBuilder, metadata, "O", Constants.NAME);
    setOID(dnBuilder, metadata, "OU", Constants.NAME);
    setOID(dnBuilder, metadata, "E", metadata.emailAddress);
    setOID(dnBuilder, metadata, "CN", metadata.commonName);
    X500Name dn = dnBuilder.build();
    return dn;
}
Also used : X500NameBuilder(org.bouncycastle.asn1.x500.X500NameBuilder) X500Name(org.bouncycastle.asn1.x500.X500Name)

Example 10 with X500NameBuilder

use of org.spongycastle.asn1.x500.X500NameBuilder in project Openfire by igniterealtime.

the class CertificateManager method createX509V3Certificate.

/**
     * Creates an X509 version3 certificate.
     *
     * @param kp           KeyPair that keeps the public and private keys for the new certificate.
     * @param days       time to live
     * @param issuerCommonName     Issuer CN string
     * @param subjectCommonName    Subject CN string
     * @param domain       Domain of the server.
     * @param signAlgoritm Signature algorithm. This can be either a name or an OID.
     * @return X509 V3 Certificate
     * @throws GeneralSecurityException
     * @throws IOException
     */
public static synchronized X509Certificate createX509V3Certificate(KeyPair kp, int days, String issuerCommonName, String subjectCommonName, String domain, String signAlgoritm) throws GeneralSecurityException, IOException {
    // subjectDN
    X500NameBuilder subjectBuilder = new X500NameBuilder();
    subjectBuilder.addRDN(BCStyle.CN, subjectCommonName);
    // issuerDN
    X500NameBuilder issuerBuilder = new X500NameBuilder();
    issuerBuilder.addRDN(BCStyle.CN, issuerCommonName);
    return createX509V3Certificate(kp, days, issuerBuilder, subjectBuilder, domain, signAlgoritm);
}
Also used : X500NameBuilder(org.bouncycastle.asn1.x500.X500NameBuilder)

Aggregations

X500NameBuilder (org.bouncycastle.asn1.x500.X500NameBuilder)12 Date (java.util.Date)9 X509Certificate (java.security.cert.X509Certificate)8 KeyPair (java.security.KeyPair)6 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)6 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)6 JcaX509v3CertificateBuilder (org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder)6 ContentSigner (org.bouncycastle.operator.ContentSigner)6 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)6 BigInteger (java.math.BigInteger)5 KeyPairGenerator (java.security.KeyPairGenerator)5 PrivateKey (java.security.PrivateKey)5 X500Name (org.bouncycastle.asn1.x500.X500Name)5 IOException (java.io.IOException)4 PublicKey (java.security.PublicKey)4 SecureRandom (java.security.SecureRandom)4 CertificateException (java.security.cert.CertificateException)4 GeneralSecurityException (java.security.GeneralSecurityException)3 KeyStore (java.security.KeyStore)3 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)3