Search in sources :

Example 21 with KeyPair

use of java.security.KeyPair in project azure-sdk-for-java by Azure.

the class CertificateOperationsTest method validatePem.

private void validatePem(CertificateBundle certificateBundle, String subjectName) throws CertificateException, IOException, KeyVaultErrorException, IllegalArgumentException, InvalidKeySpecException, NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
    // Load the CER part into X509Certificate object
    X509Certificate x509Certificate = loadCerToX509Certificate(certificateBundle);
    Assert.assertTrue(x509Certificate.getSubjectX500Principal().getName().equals(subjectName));
    Assert.assertTrue(x509Certificate.getIssuerX500Principal().getName().equals(subjectName));
    // Retrieve the secret backing the certificate
    SecretIdentifier secretIdentifier = certificateBundle.secretIdentifier();
    SecretBundle secret = keyVaultClient.getSecret(secretIdentifier.baseIdentifier());
    Assert.assertTrue(secret.managed());
    String secretValue = secret.value();
    // Extract private key from PEM
    PrivateKey secretPrivateKey = extractPrivateKeyFromPemContents(secretValue);
    Assert.assertNotNull(secretPrivateKey);
    // Extract certificates from PEM
    List<X509Certificate> certificates = extractCertificatesFromPemContents(secretValue);
    Assert.assertNotNull(certificates);
    Assert.assertTrue(certificates.size() == 1);
    // has the public key corresponding to the private key.
    X509Certificate secretCertificate = certificates.get(0);
    Assert.assertNotNull(secretCertificate);
    Assert.assertTrue(secretCertificate.getSubjectX500Principal().getName().equals(x509Certificate.getSubjectX500Principal().getName()));
    Assert.assertTrue(secretCertificate.getIssuerX500Principal().getName().equals(x509Certificate.getIssuerX500Principal().getName()));
    Assert.assertTrue(secretCertificate.getSerialNumber().equals(x509Certificate.getSerialNumber()));
    // Create a KeyPair with the private key from the KeyStore and public
    // key from the certificate to verify they match
    KeyPair keyPair = new KeyPair(secretCertificate.getPublicKey(), secretPrivateKey);
    Assert.assertNotNull(keyPair);
    verifyRSAKeyPair(keyPair);
}
Also used : SecretIdentifier(com.microsoft.azure.keyvault.SecretIdentifier) SecretBundle(com.microsoft.azure.keyvault.models.SecretBundle) KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) X509Certificate(java.security.cert.X509Certificate)

Example 22 with KeyPair

use of java.security.KeyPair in project nhin-d by DirectProject.

the class CRLRevocationManager_getCrlFromUriTest method testGetCrlFromUri_notInCache_loadFromCacheFile_assertCRLFound.

public void testGetCrlFromUri_notInCache_loadFromCacheFile_assertCRLFound() throws Exception {
    CRLRevocationManager.initCRLCacheLocation();
    String uri = "http://localhost:8080/certs.crl";
    X509CRL crl = (X509CRL) TestUtils.loadCRL("certs.crl");
    KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA", "BC");
    KeyPair pair = kpGen.generateKeyPair();
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.YEAR, cal.get(Calendar.YEAR) + 10);
    X509V2CRLGenerator crlGen = new X509V2CRLGenerator();
    crlGen.setIssuerDN(new X500Principal("CN=Test CRL"));
    crlGen.setNextUpdate(cal.getTime());
    crlGen.setSignatureAlgorithm("SHA256withRSAEncryption");
    crlGen.setThisUpdate(Calendar.getInstance().getTime());
    crlGen.addCRL(crl);
    crl = crlGen.generate(pair.getPrivate(), "BC");
    CRLRevocationManager.INSTANCE.writeCRLCacheFile(uri, crl);
    X509CRL retCrl = CRLRevocationManager.getInstance().getCrlFromUri(uri);
    assertNotNull(retCrl);
    assertEquals(crl, retCrl);
}
Also used : KeyPair(java.security.KeyPair) X509CRL(java.security.cert.X509CRL) Calendar(java.util.Calendar) X500Principal(javax.security.auth.x500.X500Principal) KeyPairGenerator(java.security.KeyPairGenerator) X509V2CRLGenerator(org.bouncycastle.x509.X509V2CRLGenerator)

Example 23 with KeyPair

use of java.security.KeyPair in project OpenAM by OpenRock.

the class AuthenticatorOathService method getEncryptionKeyPair.

private KeyPair getEncryptionKeyPair() {
    try {
        final KeyStore keyStore = new KeyStoreBuilder().withKeyStoreFile(new File(CollectionHelper.getMapAttr(options, OATH_KEYSTORE_FILE))).withPassword(CollectionHelper.getMapAttr(options, OATH_KEYSTORE_PASSWORD)).withKeyStoreType(KeyStoreType.valueOf(CollectionHelper.getMapAttr(options, OATH_KEYSTORE_TYPE))).build();
        final Certificate cert = keyStore.getCertificate(CollectionHelper.getMapAttr(options, OATH_KEYSTORE_KEYPAIR_ALIAS));
        final PublicKey publicKey = cert.getPublicKey();
        final PrivateKey privateKey = (PrivateKey) keyStore.getKey(CollectionHelper.getMapAttr(options, OATH_KEYSTORE_KEYPAIR_ALIAS), CollectionHelper.getMapAttr(options, OATH_KEYSTORE_PRIVATEKEY_PASSWORD).toCharArray());
        return new KeyPair(publicKey, privateKey);
    } catch (FileNotFoundException e) {
        throw new IllegalArgumentException("Invalid keystore location specified", e);
    } catch (KeyStoreException | UnrecoverableKeyException | NoSuchAlgorithmException e) {
        debug.error("AuthenticatorOathService.getEncryptionKeyPair(): Unable to load encryption key pair", e);
        throw new IllegalStateException(e);
    }
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) PublicKey(java.security.PublicKey) FileNotFoundException(java.io.FileNotFoundException) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreBuilder(org.forgerock.openam.shared.security.crypto.KeyStoreBuilder) KeyStore(java.security.KeyStore) UnrecoverableKeyException(java.security.UnrecoverableKeyException) File(java.io.File) Certificate(java.security.cert.Certificate)

Example 24 with KeyPair

use of java.security.KeyPair in project GNS by MobilityFirst.

the class ByteificationComparisonFail method test_201_FromCommandPacket_128B_Signed.

/**
   *
   * @param byteificationComparison
   * @throws UnsupportedEncodingException
   * @throws JSONException
   * @throws ClientException
   * @throws NoSuchAlgorithmException
   * @throws RequestParseException
   */
// FIXME: THIS TEST IS FAILING at new CommandPacket(bytes)
@Test
public void test_201_FromCommandPacket_128B_Signed(ByteificationComparisonFail byteificationComparison) throws UnsupportedEncodingException, JSONException, ClientException, NoSuchAlgorithmException, RequestParseException {
    KeyPair keyPair = KeyPairGenerator.getInstance(GNSProtocol.RSA_ALGORITHM.toString()).generateKeyPair();
    String guid = SharedGuidUtils.createGuidStringFromPublicKey(keyPair.getPublic().getEncoded());
    // Squirrel this away now just in case the call below times out.
    KeyPairUtils.saveKeyPair("gnsname", "alias", guid, keyPair);
    GuidEntry querier = new GuidEntry("alias", guid, keyPair.getPublic(), keyPair.getPrivate());
    CommandPacket packet = GNSCommand.fieldUpdate(querier, new String(Util.getRandomAlphanumericBytes(64)), new String(Util.getRandomAlphanumericBytes(64)));
    String jsonBefore = packet.toJSONObject().toString();
    byte[] bytes = packet.toBytes();
    assert (jsonBefore.equals(packet.toJSONObject().toString()));
    long startTime = System.nanoTime();
    for (int i = 0; i < TEST_RUNS; i++) {
        new CommandPacket(bytes);
    }
    long endTime = System.nanoTime();
    double avg = (endTime - startTime) / (TEST_RUNS);
    CommandPacket outputPacket = new CommandPacket(bytes);
    System.out.println("Average time CommandPacket from bytes 128B Signed was " + avg + " nanoseconds.");
    assert (Arrays.equals(bytes, outputPacket.toBytes()));
    String canonicalJSON = CanonicalJSON.getCanonicalForm(jsonBefore);
    String canonicalJSONOutput = CanonicalJSON.getCanonicalForm(outputPacket.toJSONObject());
    //System.out.println(canonicalJSONOutput);
    assert (canonicalJSON.equals(canonicalJSONOutput));
//CommandPacket outputPacket = CommandPacket.fromBytes(bytes);
//assert(packet.toJSONObject().toString().equals(outputPacket.toJSONObject().toString()));
}
Also used : KeyPair(java.security.KeyPair) CommandPacket(edu.umass.cs.gnscommon.packets.CommandPacket) GuidEntry(edu.umass.cs.gnsclient.client.util.GuidEntry) Test(org.junit.Test) DefaultGNSTest(edu.umass.cs.gnsserver.utils.DefaultGNSTest)

Example 25 with KeyPair

use of java.security.KeyPair in project jdk8u_jdk by JetBrains.

the class SignatureTest method main.

public static void main(String[] args) throws Exception {
    String testAlg = args[0];
    int testSize = Integer.parseInt(args[1]);
    byte[] data = new byte[100];
    RandomFactory.getRandom().nextBytes(data);
    // create a key pair
    KeyPair kpair = generateKeys(KEYALG, testSize);
    Key[] privs = manipulateKey(PRIVATE_KEY, kpair.getPrivate());
    Key[] pubs = manipulateKey(PUBLIC_KEY, kpair.getPublic());
    // For signature algorithm, create and verify a signature
    Arrays.stream(privs).forEach(priv -> Arrays.stream(pubs).forEach(pub -> {
        try {
            checkSignature(data, (PublicKey) pub, (PrivateKey) priv, testAlg);
        } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException | NoSuchProviderException ex) {
            throw new RuntimeException(ex);
        }
    }));
}
Also used : KeyPairGenerator(java.security.KeyPairGenerator) KeyPair(java.security.KeyPair) Arrays(java.util.Arrays) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) SignatureException(java.security.SignatureException) Signature(java.security.Signature) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PublicKey(java.security.PublicKey) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) KeyFactory(java.security.KeyFactory) Key(java.security.Key) RSAPrivateKeySpec(java.security.spec.RSAPrivateKeySpec) PUBLIC_KEY(javax.crypto.Cipher.PUBLIC_KEY) RSAPublicKey(java.security.interfaces.RSAPublicKey) RandomFactory(jdk.testlibrary.RandomFactory) PrivateKey(java.security.PrivateKey) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) RSAPublicKeySpec(java.security.spec.RSAPublicKeySpec) InvalidKeyException(java.security.InvalidKeyException) PRIVATE_KEY(javax.crypto.Cipher.PRIVATE_KEY) NoSuchProviderException(java.security.NoSuchProviderException) KeyPair(java.security.KeyPair) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PrivateKey(java.security.PrivateKey) PublicKey(java.security.PublicKey) RSAPublicKey(java.security.interfaces.RSAPublicKey) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PublicKey(java.security.PublicKey) Key(java.security.Key) RSAPublicKey(java.security.interfaces.RSAPublicKey) PrivateKey(java.security.PrivateKey)

Aggregations

KeyPair (java.security.KeyPair)903 KeyPairGenerator (java.security.KeyPairGenerator)345 Test (org.junit.Test)235 PrivateKey (java.security.PrivateKey)189 X509Certificate (java.security.cert.X509Certificate)185 PublicKey (java.security.PublicKey)167 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)127 IOException (java.io.IOException)121 BigInteger (java.math.BigInteger)87 Date (java.util.Date)78 SecureRandom (java.security.SecureRandom)75 KeyStore (java.security.KeyStore)74 GeneralSecurityException (java.security.GeneralSecurityException)63 RSAPublicKey (java.security.interfaces.RSAPublicKey)55 X500Principal (javax.security.auth.x500.X500Principal)53 File (java.io.File)52 KeyFactory (java.security.KeyFactory)52 ECPrivateKey (java.security.interfaces.ECPrivateKey)52 ECPublicKey (java.security.interfaces.ECPublicKey)52 InvalidKeyException (java.security.InvalidKeyException)40