Search in sources :

Example 91 with PrivateKey

use of java.security.PrivateKey in project wycheproof by google.

the class DhiesTest method testDhiesCorrupt.

/**
   * WARNING: This test uses weak crypto (i.e. DHIESWithAES). DHIES should be secure against chosen
   * ciphertexts. Checks that a modification of the ciphertext is dectected.
   */
@SlowTest(providers = { ProviderType.BOUNCY_CASTLE, ProviderType.SPONGY_CASTLE })
@SuppressWarnings("InsecureCryptoUsage")
public void testDhiesCorrupt() throws Exception {
    KeyPairGenerator kf = KeyPairGenerator.getInstance("DH");
    kf.initialize(ike2048());
    KeyPair keyPair = kf.generateKeyPair();
    PrivateKey priv = keyPair.getPrivate();
    PublicKey pub = keyPair.getPublic();
    byte[] message = new byte[32];
    Cipher dhies;
    try {
        dhies = Cipher.getInstance("DHIESwithAES");
    } catch (NoSuchAlgorithmException ex) {
        // The algorithm isn't supported - even better!
        return;
    }
    dhies.init(Cipher.ENCRYPT_MODE, pub);
    byte[] ciphertext = dhies.doFinal(message);
    for (int i = 0; i < ciphertext.length; i++) {
        byte[] corrupt = Arrays.copyOf(ciphertext, ciphertext.length);
        corrupt[i] ^= (byte) 1;
        try {
            dhies.init(Cipher.DECRYPT_MODE, priv);
            dhies.doFinal(corrupt);
            fail("Corrupt ciphertext accepted:" + i);
        } catch (GeneralSecurityException ex) {
        // This is expected
        }
    }
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) PublicKey(java.security.PublicKey) GeneralSecurityException(java.security.GeneralSecurityException) KeyPairGenerator(java.security.KeyPairGenerator) Cipher(javax.crypto.Cipher) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SlowTest(com.google.security.wycheproof.WycheproofRunner.SlowTest)

Example 92 with PrivateKey

use of java.security.PrivateKey in project gitblit by gitblit.

the class X509UtilsTest method testCertificateUserMapping.

@Test
public void testCertificateUserMapping() throws Exception {
    File storeFile = new File(folder, X509Utils.CA_KEY_STORE);
    PrivateKey caPrivateKey = X509Utils.getPrivateKey(X509Utils.CA_ALIAS, storeFile, caPassword);
    X509Certificate caCert = X509Utils.getCertificate(X509Utils.CA_ALIAS, storeFile, caPassword);
    X509Metadata userMetadata = new X509Metadata("james", "james");
    userMetadata.serverHostname = "www.myserver.com";
    userMetadata.userDisplayname = "James Moger";
    userMetadata.passwordHint = "your name";
    userMetadata.oids.put("C", "US");
    X509Certificate cert1 = X509Utils.newClientCertificate(userMetadata, caPrivateKey, caCert, storeFile.getParentFile());
    UserModel userModel1 = HttpUtils.getUserModelFromCertificate(cert1);
    assertEquals(userMetadata.commonName, userModel1.username);
    assertEquals(userMetadata.emailAddress, userModel1.emailAddress);
    assertEquals("C=US,O=Gitblit,OU=Gitblit,CN=james", cert1.getSubjectDN().getName());
    X509Certificate cert2 = X509Utils.newClientCertificate(userMetadata, caPrivateKey, caCert, storeFile.getParentFile());
    UserModel userModel2 = HttpUtils.getUserModelFromCertificate(cert2);
    assertEquals(userMetadata.commonName, userModel2.username);
    assertEquals(userMetadata.emailAddress, userModel2.emailAddress);
    assertEquals("C=US,O=Gitblit,OU=Gitblit,CN=james", cert2.getSubjectDN().getName());
    assertNotSame("Serial numbers are the same!", cert1.getSerialNumber().longValue(), cert2.getSerialNumber().longValue());
}
Also used : UserModel(com.gitblit.models.UserModel) PrivateKey(java.security.PrivateKey) X509Metadata(com.gitblit.utils.X509Utils.X509Metadata) File(java.io.File) X509Certificate(java.security.cert.X509Certificate) Test(org.junit.Test)

Example 93 with PrivateKey

use of java.security.PrivateKey in project gitblit by gitblit.

the class X509UtilsTest method testCertificateRevocation.

@Test
public void testCertificateRevocation() throws Exception {
    File storeFile = new File(folder, X509Utils.CA_KEY_STORE);
    PrivateKey caPrivateKey = X509Utils.getPrivateKey(X509Utils.CA_ALIAS, storeFile, caPassword);
    X509Certificate caCert = X509Utils.getCertificate(X509Utils.CA_ALIAS, storeFile, caPassword);
    X509Metadata userMetadata = new X509Metadata("james", "james");
    userMetadata.serverHostname = "www.myserver.com";
    userMetadata.userDisplayname = "James Moger";
    userMetadata.passwordHint = "your name";
    // generate a new client certificate
    X509Certificate cert1 = X509Utils.newClientCertificate(userMetadata, caPrivateKey, caCert, storeFile.getParentFile());
    // confirm this certificate IS NOT revoked
    File caRevocationList = new File(folder, X509Utils.CA_REVOCATION_LIST);
    assertFalse(X509Utils.isRevoked(cert1, caRevocationList));
    // revoke certificate and then confirm it IS revoked
    X509Utils.revoke(cert1, RevocationReason.ACompromise, caRevocationList, storeFile, caPassword, log);
    assertTrue(X509Utils.isRevoked(cert1, caRevocationList));
    // generate a second certificate
    X509Certificate cert2 = X509Utils.newClientCertificate(userMetadata, caPrivateKey, caCert, storeFile.getParentFile());
    // confirm second certificate IS NOT revoked
    assertTrue(X509Utils.isRevoked(cert1, caRevocationList));
    assertFalse(X509Utils.isRevoked(cert2, caRevocationList));
    // revoke second certificate and then confirm it IS revoked
    X509Utils.revoke(cert2, RevocationReason.ACompromise, caRevocationList, caPrivateKey, log);
    assertTrue(X509Utils.isRevoked(cert1, caRevocationList));
    assertTrue(X509Utils.isRevoked(cert2, caRevocationList));
    // generate a third certificate
    X509Certificate cert3 = X509Utils.newClientCertificate(userMetadata, caPrivateKey, caCert, storeFile.getParentFile());
    // confirm third certificate IS NOT revoked
    assertTrue(X509Utils.isRevoked(cert1, caRevocationList));
    assertTrue(X509Utils.isRevoked(cert2, caRevocationList));
    assertFalse(X509Utils.isRevoked(cert3, caRevocationList));
    // revoke third certificate and then confirm it IS revoked
    X509Utils.revoke(cert3, RevocationReason.ACompromise, caRevocationList, caPrivateKey, log);
    assertTrue(X509Utils.isRevoked(cert1, caRevocationList));
    assertTrue(X509Utils.isRevoked(cert2, caRevocationList));
    assertTrue(X509Utils.isRevoked(cert3, caRevocationList));
}
Also used : PrivateKey(java.security.PrivateKey) X509Metadata(com.gitblit.utils.X509Utils.X509Metadata) File(java.io.File) X509Certificate(java.security.cert.X509Certificate) Test(org.junit.Test)

Example 94 with PrivateKey

use of java.security.PrivateKey in project gocd by gocd.

the class RegistrationJSONizer method fromJson.

public static Registration fromJson(String json) {
    Map map = GSON.fromJson(json, Map.class);
    if (map.isEmpty()) {
        return Registration.createNullPrivateKeyEntry();
    }
    List<Certificate> chain = new ArrayList<>();
    try {
        PemReader reader = new PemReader(new StringReader((String) map.get("agentPrivateKey")));
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(reader.readPemObject().getContent());
        PrivateKey privateKey = kf.generatePrivate(spec);
        String agentCertificate = (String) map.get("agentCertificate");
        PemReader certReader = new PemReader(new StringReader(agentCertificate));
        while (true) {
            PemObject obj = certReader.readPemObject();
            if (obj == null) {
                break;
            }
            chain.add(CertificateFactory.getInstance("X.509").generateCertificate(new ByteArrayInputStream(obj.getContent())));
        }
        return new Registration(privateKey, chain.toArray(new Certificate[chain.size()]));
    } catch (IOException | NoSuchAlgorithmException | CertificateException | InvalidKeySpecException e) {
        throw bomb(e);
    }
}
Also used : PrivateKey(java.security.PrivateKey) ArrayList(java.util.ArrayList) CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) PemReader(org.bouncycastle.util.io.pem.PemReader) PemObject(org.bouncycastle.util.io.pem.PemObject) ByteArrayInputStream(java.io.ByteArrayInputStream) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) StringReader(java.io.StringReader) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) HashMap(java.util.HashMap) Map(java.util.Map) KeyFactory(java.security.KeyFactory) Certificate(java.security.cert.Certificate)

Example 95 with PrivateKey

use of java.security.PrivateKey in project gitblit by gitblit.

the class X509Utils method newCertificateRevocationList.

/**
	 * Creates a new certificate revocation list (CRL).  This function will
	 * destroy any existing CRL file.
	 *
	 * @param caRevocationList
	 * @param storeFile
	 * @param keystorePassword
	 * @return
	 */
public static void newCertificateRevocationList(File caRevocationList, File caKeystoreFile, String caKeystorePassword) {
    try {
        // read the Gitblit CA key and certificate
        KeyStore store = openKeyStore(caKeystoreFile, caKeystorePassword);
        PrivateKey caPrivateKey = (PrivateKey) store.getKey(CA_ALIAS, caKeystorePassword.toCharArray());
        X509Certificate caCert = (X509Certificate) store.getCertificate(CA_ALIAS);
        X500Name issuerDN = new X500Name(PrincipalUtil.getIssuerX509Principal(caCert).getName());
        X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(issuerDN, new Date());
        // build and sign CRL with CA private key
        ContentSigner signer = new JcaContentSignerBuilder(SIGNING_ALGORITHM).setProvider(BC).build(caPrivateKey);
        X509CRLHolder crl = crlBuilder.build(signer);
        File tmpFile = new File(caRevocationList.getParentFile(), Long.toHexString(System.currentTimeMillis()) + ".tmp");
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(tmpFile);
            fos.write(crl.getEncoded());
            fos.flush();
            fos.close();
            if (caRevocationList.exists()) {
                caRevocationList.delete();
            }
            tmpFile.renameTo(caRevocationList);
        } finally {
            if (fos != null) {
                fos.close();
            }
            if (tmpFile.exists()) {
                tmpFile.delete();
            }
        }
    } catch (Exception e) {
        throw new RuntimeException("Failed to create new certificate revocation list " + caRevocationList, e);
    }
}
Also used : PrivateKey(java.security.PrivateKey) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) X500Name(org.bouncycastle.asn1.x500.X500Name) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) Date(java.util.Date) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) SignatureException(java.security.SignatureException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) CertificateEncodingException(java.security.cert.CertificateEncodingException) CertPathBuilderException(java.security.cert.CertPathBuilderException) IOException(java.io.IOException) FileOutputStream(java.io.FileOutputStream) X509CRLHolder(org.bouncycastle.cert.X509CRLHolder) X509v2CRLBuilder(org.bouncycastle.cert.X509v2CRLBuilder) File(java.io.File)

Aggregations

PrivateKey (java.security.PrivateKey)517 X509Certificate (java.security.cert.X509Certificate)217 KeyFactory (java.security.KeyFactory)169 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)144 Certificate (java.security.cert.Certificate)127 PublicKey (java.security.PublicKey)120 ByteArrayInputStream (java.io.ByteArrayInputStream)118 KeyStore (java.security.KeyStore)93 CertificateFactory (java.security.cert.CertificateFactory)92 IOException (java.io.IOException)81 Key (java.security.Key)74 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)73 PrivateKeyEntry (java.security.KeyStore.PrivateKeyEntry)70 Entry (java.security.KeyStore.Entry)60 TrustedCertificateEntry (java.security.KeyStore.TrustedCertificateEntry)60 KeyPair (java.security.KeyPair)59 SecretKey (javax.crypto.SecretKey)48 InvalidKeyException (java.security.InvalidKeyException)47 KeyStoreException (java.security.KeyStoreException)46 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)46