java.security.KeyPair

Here are the examples of the java api class java.security.KeyPair taken from open source projects.

1. UserProfileTest#testGetFileById()

Project: Hive2Hive
Source File: UserProfileTest.java
View license
@Test
public void testGetFileById() {
    FolderIndex root = userProfile.getRoot();
    KeyPair child1Key = generateRSAKeyPair(RSA_KEYLENGTH.BIT_512);
    FolderIndex child1Folder = new FolderIndex(root, child1Key, randomString());
    KeyPair child2Key = generateRSAKeyPair(RSA_KEYLENGTH.BIT_1024);
    new FileIndex(root, child2Key, randomString(), "bla".getBytes());
    KeyPair child3Key = generateRSAKeyPair(RSA_KEYLENGTH.BIT_2048);
    new FileIndex(child1Folder, child3Key, randomString(), "blubb".getBytes());
    Assert.assertNotNull(userProfile.getFileById(child1Key.getPublic()));
    Assert.assertNotNull(userProfile.getFileById(child2Key.getPublic()));
    Assert.assertNotNull(userProfile.getFileById(child3Key.getPublic()));
}

2. KeyPairs#create()

Project: eucalyptus
Source File: KeyPairs.java
View license
public static PrivateKey create(UserFullName userName, String keyName) throws MetadataException, TransactionException {
    SshKeyPair newKey = SshKeyPair.create(userName, keyName);
    KeyPair newKeys = null;
    try {
        newKeys = Certs.generateKeyPair();
        String authKeyString = KeyPairs.getAuthKeyString(userName, keyName, newKeys);
        newKey.setPublicKey(authKeyString);
        newKey.setFingerPrint(Certs.getFingerPrint(newKeys.getPrivate()));
    } catch (Exception e) {
        throw new MetadataCreationException("KeyPair generation error: Key pair creation failed.", e);
    }
    try {
        Transactions.save(newKey);
    } catch (ConstraintViolationException ex) {
        Logs.exhaust().error(ex);
        throw new DuplicateMetadataException("Failed to create keypair '" + keyName + "', already exists.");
    }
    return newKeys.getPrivate();
}

3. I52#test()

Project: fast-serialization
Source File: I52.java
View license
@Test
public void test() throws Exception {
    // install BouncyCastle provider
    Security.addProvider(new BouncyCastleProvider());
    // generate a keypair
    KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA", "BC");
    RSAKeyGenParameterSpec params = new RSAKeyGenParameterSpec(STRENGTH, PUBLIC_EXP);
    gen.initialize(params, new SecureRandom());
    KeyPair keyPair = gen.generateKeyPair();
    FSTConfiguration fst = FSTConfiguration.createDefaultConfiguration();
    // serialize
    byte[] serialized = fst.asByteArray(keyPair);
    // deserialize --> crash
    KeyPair deserialized = (KeyPair) fst.asObject(serialized);
}

4. UserProfileCreationStep#doExecute()

View license
@Override
protected Void doExecute() throws InvalidProcessStateException, ProcessExecutionException {
    String userId = context.consumeUserId();
    logger.trace("Creating new user profile. user id ='{}'", userId);
    // generate keys
    KeyPair encryptionKeys = encryption.generateRSAKeyPair(H2HConstants.KEYLENGTH_USER_KEYS);
    KeyPair protectionKeys = encryption.generateRSAKeyPair(H2HConstants.KEYLENGTH_PROTECTION);
    context.provideUserProfile(new UserProfile(userId, encryptionKeys, protectionKeys));
    return null;
}

5. SerializerTest#testKeyPair()

Project: Hive2Hive
Source File: SerializerTest.java
View license
@Test
public void testKeyPair() throws IOException, ClassNotFoundException {
    // install the provider anyway because probably key pairs need to be generated
    if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
        Security.addProvider(new BouncyCastleProvider());
    }
    KeyPair keyPair = generateRSAKeyPair(RSA_KEYLENGTH.BIT_512);
    byte[] encoded = serializer.serialize(keyPair);
    KeyPair decoded = (KeyPair) serializer.deserialize(encoded);
    assertEquals(keyPair.getPrivate(), decoded.getPrivate());
    assertEquals(keyPair.getPublic(), decoded.getPublic());
}

6. NetworkTestUtil#setSameSession()

Project: Hive2Hive
Source File: NetworkTestUtil.java
View license
/**
	 * Generate and assign a public/private key pair to all nodes.
	 * 
	 * @param network
	 *            list containing all nodes which need to have the same key pair
	 * @throws NoPeerConnectionException
	 */
public static void setSameSession(List<NetworkManager> network) throws NoPeerConnectionException {
    KeyPair keyPair = H2HJUnitTest.generateRSAKeyPair(H2HConstants.KEYLENGTH_USER_KEYS);
    KeyPair protectionKeys = H2HJUnitTest.generateRSAKeyPair(H2HConstants.KEYLENGTH_USER_KEYS);
    UserCredentials userCredentials = H2HJUnitTest.generateRandomCredentials();
    for (NetworkManager node : network) {
        UserProfileManager profileManager = new UserProfileManager(node.getDataManager(), userCredentials);
        PublicKeyManager keyManager = new PublicKeyManager(userCredentials.getUserId(), keyPair, protectionKeys, node.getDataManager());
        DownloadManager downloadManager = new DownloadManager(node, new TestFileConfiguration());
        LocationsManager locationsManager = new LocationsManager(node.getDataManager(), userCredentials.getUserId(), protectionKeys);
        SessionParameters params = new SessionParameters(new TestFileAgent());
        params.setDownloadManager(downloadManager);
        params.setKeyManager(keyManager);
        params.setUserProfileManager(profileManager);
        params.setLocationsManager(locationsManager);
        node.setSession(new H2HSession(params));
    }
}

7. AbstractHttpClientTest#testVerifyResponseFailure()

Project: kaa
Source File: AbstractHttpClientTest.java
View license
@Test(expected = GeneralSecurityException.class)
public void testVerifyResponseFailure() throws NoSuchAlgorithmException, GeneralSecurityException {
    KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
    gen.initialize(512);
    KeyPair clientKeyPair = gen.generateKeyPair();
    KeyPair remoteKeyPair = gen.generateKeyPair();
    TestHttpClient client = new TestHttpClient("test_url", clientKeyPair.getPrivate(), clientKeyPair.getPublic(), remoteKeyPair.getPublic());
    byte[] body = { 1, 2, 3 };
    byte[] signature = { 1, 2, 3 };
    client.verifyResponse(body, signature);
}

8. AbstractHttpClientTest#testSignature()

Project: kaa
Source File: AbstractHttpClientTest.java
View license
@Test
public void testSignature() throws NoSuchAlgorithmException, GeneralSecurityException {
    KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
    gen.initialize(512);
    KeyPair clientKeyPair = gen.generateKeyPair();
    KeyPair remoteKeyPair = gen.generateKeyPair();
    TestHttpClient client = new TestHttpClient("test_url", clientKeyPair.getPrivate(), clientKeyPair.getPublic(), remoteKeyPair.getPublic());
    MessageEncoderDecoder serverEncoder = new MessageEncoderDecoder(remoteKeyPair.getPrivate(), remoteKeyPair.getPublic());
    byte[] message = { 1, 2, 3 };
    byte[] signature = serverEncoder.sign(message);
    Assert.assertArrayEquals(message, client.verifyResponse(message, signature));
    Assert.assertTrue(client.getEncoderDecoder().verify(message, signature));
}

9. SecurityUtilsTest#testLoadPrivateKey()

Project: mina-sshd
Source File: SecurityUtilsTest.java
View license
private static KeyPair testLoadPrivateKey(String resourceKey, AbstractResourceKeyPairProvider<?> provider, Class<? extends PublicKey> pubType, Class<? extends PrivateKey> prvType) {
    provider.setPasswordFinder(TEST_PASSWORD_PROVIDER);
    Iterable<KeyPair> iterator = provider.loadKeys();
    List<KeyPair> pairs = new ArrayList<KeyPair>();
    for (KeyPair kp : iterator) {
        pairs.add(kp);
    }
    assertEquals("Mismatched loaded pairs count for " + resourceKey, 1, pairs.size());
    KeyPair kp = pairs.get(0);
    PublicKey pub = kp.getPublic();
    assertNotNull("No public key extracted", pub);
    assertTrue("Not an " + pubType.getSimpleName() + " public key for " + resourceKey, pubType.isAssignableFrom(pub.getClass()));
    PrivateKey prv = kp.getPrivate();
    assertNotNull("No private key extracted", prv);
    assertTrue("Not an " + prvType.getSimpleName() + " private key for " + resourceKey, prvType.isAssignableFrom(prv.getClass()));
    return kp;
}

10. PEMGeneratorHostKeyProviderTest#testPEMGeneratorHostKeyProvider()

View license
private Path testPEMGeneratorHostKeyProvider(String algorithm, String keyType, int keySize, AlgorithmParameterSpec keySpec) throws IOException {
    Path path = initKeyFileLocation(algorithm);
    KeyPair kpWrite = invokePEMGeneratorHostKeyProvider(path, algorithm, keyType, keySize, keySpec);
    assertTrue("Key file not generated: " + path, Files.exists(path, IoUtils.EMPTY_LINK_OPTIONS));
    KeyPair kpRead = invokePEMGeneratorHostKeyProvider(path, algorithm, keyType, keySize, keySpec);
    PublicKey pubWrite = kpWrite.getPublic();
    PublicKey pubRead = kpRead.getPublic();
    if (pubWrite instanceof ECPublicKey) {
        // The algorithm is reported as ECDSA instead of EC
        assertECPublicKeyEquals("Mismatched EC public key", ECPublicKey.class.cast(pubWrite), ECPublicKey.class.cast(pubRead));
    } else {
        assertKeyEquals("Mismatched public keys", pubWrite, pubRead);
    }
    return path;
}

11. CertificateGenEncryptUtilTest#testPrivateAnotherPublic()

View license
@Test
public void testPrivateAnotherPublic() {
    byte[] pat = pattern.getBytes();
    KeyPair kp = CertificateGenEncryptUtil.generateKeyPair();
    byte[] encr = CertificateGenEncryptUtil.encryptUsingKey(pat, kp.getPrivate());
    KeyPair kp1 = CertificateGenEncryptUtil.generateKeyPair();
    try {
        byte[] decr = CertificateGenEncryptUtil.decryptUsingKey(encr, kp1.getPublic());
        assertFalse(Arrays.equals(encr, decr));
        fail();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    byte[] decr = CertificateGenEncryptUtil.decryptUsingKey(encr, kp.getPublic());
    assertTrue(Arrays.equals(pat, decr));
}

12. SigningTest#setup()

Project: Resteasy
Source File: SigningTest.java
View license
@BeforeClass
public static void setup() throws Exception {
    Logger.setLoggerType(Logger.LoggerType.JUL);
    repository = new DosetaKeyRepository();
    repository.setKeyStorePath("test.jks");
    repository.setKeyStorePassword("password");
    repository.setUseDns(false);
    repository.start();
    PrivateKey privateKey = repository.getKeyStore().getPrivateKey("test._domainKey.samplezone.org");
    if (privateKey == null)
        throw new Exception("Private Key is null!!!");
    PublicKey publicKey = repository.getKeyStore().getPublicKey("test._domainKey.samplezone.org");
    keys = new KeyPair(publicKey, privateKey);
    KeyPair keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
    badKey = keyPair.getPrivate();
    dispatcher.getDefaultContextObjects().put(KeyRepository.class, repository);
    addPerRequestResource(SignedResource.class);
    client = new ResteasyClientBuilder().build();
}

13. VerifyAnnotationNoEntityTest#setup()

View license
@BeforeClass
public static void setup() throws Exception {
    Logger.setLoggerType(Logger.LoggerType.JUL);
    repository = new DosetaKeyRepository();
    repository.setKeyStorePath("test.jks");
    repository.setKeyStorePassword("password");
    repository.setUseDns(false);
    repository.start();
    PrivateKey privateKey = repository.getKeyStore().getPrivateKey("test._domainKey.samplezone.org");
    if (privateKey == null)
        throw new Exception("Private Key is null!!!");
    PublicKey publicKey = repository.getKeyStore().getPublicKey("test._domainKey.samplezone.org");
    keys = new KeyPair(publicKey, privateKey);
    KeyPair keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
    badKey = keyPair.getPrivate();
    dispatcher.getDefaultContextObjects().put(KeyRepository.class, repository);
    addPerRequestResource(SignedResource.class);
    client = new ResteasyClientBuilder().build();
}

14. LocalTest#setup()

Project: Resteasy
Source File: LocalTest.java
View license
@BeforeClass
public static void setup() throws Exception {
    Logger.setLoggerType(Logger.LoggerType.JUL);
    repository = new DosetaKeyRepository();
    repository.setKeyStorePath("test.jks");
    repository.setKeyStorePassword("password");
    repository.setUseDns(false);
    repository.start();
    PrivateKey privateKey = repository.getKeyStore().getPrivateKey("test._domainKey.samplezone.org");
    if (privateKey == null)
        throw new Exception("Private Key is null!!!");
    PublicKey publicKey = repository.getKeyStore().getPublicKey("test._domainKey.samplezone.org");
    keys = new KeyPair(publicKey, privateKey);
    KeyPair keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
}

15. TestData#testData6()

Project: TomP2P
Source File: TestData.java
View license
@Test
public void testData6() throws IOException, ClassNotFoundException, NoSuchAlgorithmException, InvalidKeyException, SignatureException {
    KeyPairGenerator gen = KeyPairGenerator.getInstance("DSA");
    KeyPair keyPair1 = gen.generateKeyPair();
    KeyPair keyPair2 = gen.generateKeyPair();
    Data data = new Data(new byte[10000]);
    data.signNow(keyPair1, factory);
    Data newData = encodeDecode(data);
    Assert.assertTrue(newData.verify(keyPair1.getPublic(), factory));
    Assert.assertFalse(newData.verify(keyPair2.getPublic(), factory));
    Assert.assertEquals(data, newData);
}

16. TestData#testDataBasedOn3()

Project: TomP2P
Source File: TestData.java
View license
@Test
public void testDataBasedOn3() throws IOException, ClassNotFoundException, InvalidKeyException, SignatureException, NoSuchAlgorithmException {
    Random random = new Random();
    KeyPairGenerator gen = KeyPairGenerator.getInstance("DSA");
    KeyPair keyPair1 = gen.generateKeyPair();
    KeyPair keyPair2 = gen.generateKeyPair();
    Data data = new Data(UUID.randomUUID().toString());
    data.ttlSeconds(random.nextInt());
    for (int i = 0; i < 255; i++) {
        data.addBasedOn(new Number160(random));
    }
    // data.setProtectedEntry().publicKey(gen.generateKeyPair().getPublic());
    data.signNow(keyPair1, factory);
    Data newData = encodeDecode(data);
    Assert.assertEquals(data.object(), newData.object());
    Assert.assertEquals(data.ttlSeconds(), newData.ttlSeconds());
    Assert.assertEquals(data.basedOnSet(), newData.basedOnSet());
    Assert.assertTrue(newData.verify(keyPair1.getPublic(), factory));
    Assert.assertFalse(newData.verify(keyPair2.getPublic(), factory));
    Assert.assertEquals(data, newData);
}

17. TestStorage#testPublicKeyDomain()

Project: TomP2P
Source File: TestStorage.java
View license
private void testPublicKeyDomain(StorageLayer storage) throws Exception {
    KeyPairGenerator gen = KeyPairGenerator.getInstance("DSA");
    KeyPair pair1 = gen.generateKeyPair();
    KeyPair pair2 = gen.generateKeyPair();
    store(storage, pair1.getPublic(), true);
    Enum<?> result1 = storage.put(key3, new Data("test4"), pair1.getPublic(), false, false, false);
    Assert.assertEquals(PutStatus.OK, result1);
    Enum<?> result3 = storage.put(key3, new Data("test6"), pair1.getPublic(), false, true, false);
    Assert.assertEquals(PutStatus.OK, result3);
    // domain is protected by pair1
    Enum<?> result2 = storage.put(key3, new Data("test5"), pair2.getPublic(), false, true, false);
    Assert.assertEquals(PutStatus.FAILED_SECURITY, result2);
}

18. TestStorage#testPublicKeyDomain()

Project: TomP2P
Source File: TestStorage.java
View license
private void testPublicKeyDomain(StorageLayer storage) throws Exception {
    KeyPairGenerator gen = KeyPairGenerator.getInstance("DSA");
    KeyPair pair1 = gen.generateKeyPair();
    KeyPair pair2 = gen.generateKeyPair();
    store(storage, pair1.getPublic(), true);
    Enum<?> result1 = storage.put(key3, new Data("test4"), pair1.getPublic(), false, false, false);
    Assert.assertEquals(PutStatus.OK, result1);
    Enum<?> result3 = storage.put(key3, new Data("test6"), pair1.getPublic(), false, true, false);
    Assert.assertEquals(PutStatus.OK, result3);
    // domain is protected by pair1
    Enum<?> result2 = storage.put(key3, new Data("test5"), pair2.getPublic(), false, true, false);
    Assert.assertEquals(PutStatus.FAILED_SECURITY, result2);
}

19. PGPKeyRingTest#testNoExportPrivateKey()

Project: bc-java
Source File: PGPKeyRingTest.java
View license
public void testNoExportPrivateKey() throws Exception {
    KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA", "BC");
    kpGen.initialize(1024);
    KeyPair kp = kpGen.generateKeyPair();
    JcaPGPKeyConverter converter = new JcaPGPKeyConverter();
    PGPPublicKey pubKey = converter.getPGPPublicKey(PGPPublicKey.RSA_GENERAL, kp.getPublic(), new Date());
    PGPPrivateKey privKey = new JcaPGPPrivateKey(pubKey, kp.getPrivate());
    doTestNoExportPrivateKey(new PGPKeyPair(pubKey, privKey));
}

20. PGPKeyRingTest#testNoExportPrivateKey()

Project: bc-java
Source File: PGPKeyRingTest.java
View license
public void testNoExportPrivateKey() throws Exception {
    KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA", "BC");
    kpGen.initialize(1024);
    KeyPair kp = kpGen.generateKeyPair();
    JcaPGPKeyConverter converter = new JcaPGPKeyConverter();
    PGPPublicKey pubKey = converter.getPGPPublicKey(PGPPublicKey.RSA_GENERAL, kp.getPublic(), new Date());
    PGPPrivateKey privKey = new JcaPGPPrivateKey(pubKey, kp.getPrivate());
    doTestNoExportPrivateKey(new PGPKeyPair(pubKey, privKey));
}

21. AllTests#testMacProtectedMessage()

Project: bc-java
Source File: AllTests.java
View license
public void testMacProtectedMessage() throws Exception {
    KeyPairGenerator kGen = KeyPairGenerator.getInstance("RSA", BC);
    kGen.initialize(512);
    KeyPair kp = kGen.generateKeyPair();
    X509CertificateHolder cert = makeV3Certificate(kp, "CN=Test", kp, "CN=Test");
    GeneralName sender = new GeneralName(new X500Name("CN=Sender"));
    GeneralName recipient = new GeneralName(new X500Name("CN=Recip"));
    ProtectedPKIMessage message = new ProtectedPKIMessageBuilder(sender, recipient).setBody(new PKIBody(PKIBody.TYPE_INIT_REP, CertRepMessage.getInstance(new DERSequence(new DERSequence())))).addCMPCertificate(cert).build(new PKMACBuilder(new JcePKMACValuesCalculator().setProvider(BC)).build("secret".toCharArray()));
    PKMACBuilder pkMacBuilder = new PKMACBuilder(new JcePKMACValuesCalculator().setProvider(BC));
    assertTrue(message.verify(pkMacBuilder, "secret".toCharArray()));
    assertEquals(sender, message.getHeader().getSender());
    assertEquals(recipient, message.getHeader().getRecipient());
}

22. AllTests#testNotBeforeNotAfter()

Project: bc-java
Source File: AllTests.java
View license
public void testNotBeforeNotAfter() throws Exception {
    KeyPairGenerator kGen = KeyPairGenerator.getInstance("RSA", BC);
    kGen.initialize(512);
    KeyPair kp = kGen.generateKeyPair();
    doNotBeforeNotAfterTest(kp, new Date(0L), new Date(60000L));
    doNotBeforeNotAfterTest(kp, null, new Date(60000L));
    doNotBeforeNotAfterTest(kp, new Date(0L), null);
}

23. AllTests#testEncryptedValue()

Project: bc-java
Source File: AllTests.java
View license
public void testEncryptedValue() throws Exception {
    KeyPairGenerator kGen = KeyPairGenerator.getInstance("RSA", BC);
    kGen.initialize(512);
    KeyPair kp = kGen.generateKeyPair();
    X509Certificate cert = makeV1Certificate(kp, "CN=Test", kp, "CN=Test");
    JcaEncryptedValueBuilder build = new JcaEncryptedValueBuilder(new JceAsymmetricKeyWrapper(cert.getPublicKey()).setProvider(BC), new JceCRMFEncryptorBuilder(CMSAlgorithm.AES128_CBC).setProvider(BC).build());
    EncryptedValue value = build.build(cert);
    ValueDecryptorGenerator decGen = new JceAsymmetricValueDecryptorGenerator(kp.getPrivate()).setProvider(BC);
    // try direct
    encryptedValueParserTest(value, decGen, cert);
    // try indirect
    encryptedValueParserTest(EncryptedValue.getInstance(value.getEncoded()), decGen, cert);
}

24. AllTests#testEncryptedValuePassphrase()

Project: bc-java
Source File: AllTests.java
View license
public void testEncryptedValuePassphrase() throws Exception {
    char[] passphrase = PASSPHRASE.toCharArray();
    KeyPairGenerator kGen = KeyPairGenerator.getInstance("RSA", BC);
    kGen.initialize(512);
    KeyPair kp = kGen.generateKeyPair();
    X509Certificate cert = makeV1Certificate(kp, "CN=Test", kp, "CN=Test");
    EncryptedValueBuilder build = new EncryptedValueBuilder(new JceAsymmetricKeyWrapper(cert.getPublicKey()).setProvider(BC), new JceCRMFEncryptorBuilder(CMSAlgorithm.AES128_CBC).setProvider(BC).build());
    EncryptedValue value = build.build(passphrase);
    ValueDecryptorGenerator decGen = new JceAsymmetricValueDecryptorGenerator(kp.getPrivate()).setProvider(BC);
    // try direct
    encryptedValuePassphraseParserTest(value, null, decGen, cert);
    // try indirect
    encryptedValuePassphraseParserTest(EncryptedValue.getInstance(value.getEncoded()), null, decGen, cert);
}

25. AllTests#testEncryptedValuePassphraseWithPadding()

Project: bc-java
Source File: AllTests.java
View license
public void testEncryptedValuePassphraseWithPadding() throws Exception {
    char[] passphrase = PASSPHRASE.toCharArray();
    KeyPairGenerator kGen = KeyPairGenerator.getInstance("RSA", BC);
    kGen.initialize(512);
    KeyPair kp = kGen.generateKeyPair();
    X509Certificate cert = makeV1Certificate(kp, "CN=Test", kp, "CN=Test");
    BcFixedLengthMGF1Padder mgf1Padder = new BcFixedLengthMGF1Padder(200, new SecureRandom());
    EncryptedValueBuilder build = new EncryptedValueBuilder(new JceAsymmetricKeyWrapper(cert.getPublicKey()).setProvider(BC), new JceCRMFEncryptorBuilder(CMSAlgorithm.AES128_CBC).setProvider(BC).build(), mgf1Padder);
    EncryptedValue value = build.build(passphrase);
    ValueDecryptorGenerator decGen = new JceAsymmetricValueDecryptorGenerator(kp.getPrivate()).setProvider(BC);
    // try direct
    encryptedValuePassphraseParserTest(value, mgf1Padder, decGen, cert);
    // try indirect
    encryptedValuePassphraseParserTest(EncryptedValue.getInstance(value.getEncoded()), mgf1Padder, decGen, cert);
}

26. ParserTest#keyDecryptTest()

Project: bc-java
Source File: ParserTest.java
View license
private void keyDecryptTest(String fileName, Class expectedPrivKeyClass, PEMDecryptorProvider decProv) throws IOException {
    PEMParser pr = openPEMResource("data/" + fileName);
    Object o = pr.readObject();
    if (o == null || !((o instanceof PEMKeyPair) || (o instanceof PEMEncryptedKeyPair))) {
        fail("Didn't find OpenSSL key");
    }
    JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
    KeyPair kp = (o instanceof PEMEncryptedKeyPair) ? converter.getKeyPair(((PEMEncryptedKeyPair) o).decryptKeyPair(decProv)) : converter.getKeyPair((PEMKeyPair) o);
    PrivateKey privKey = kp.getPrivate();
    if (!expectedPrivKeyClass.isInstance(privKey)) {
        fail("Returned key not of correct type");
    }
}

27. AllTests#testOaepWrap()

Project: bc-java
Source File: AllTests.java
View license
public void testOaepWrap() throws Exception {
    KeyPairGenerator kGen = KeyPairGenerator.getInstance("RSA", BC);
    kGen.initialize(2048);
    KeyPair kp = kGen.generateKeyPair();
    checkAlgorithmId(kp, "SHA-1", OIWObjectIdentifiers.idSHA1);
    checkAlgorithmId(kp, "SHA-224", NISTObjectIdentifiers.id_sha224);
    checkAlgorithmId(kp, "SHA-256", NISTObjectIdentifiers.id_sha256);
    checkAlgorithmId(kp, "SHA-384", NISTObjectIdentifiers.id_sha384);
    checkAlgorithmId(kp, "SHA-512", NISTObjectIdentifiers.id_sha512);
    checkAlgorithmId(kp, "SHA-512/224", NISTObjectIdentifiers.id_sha512_224);
    checkAlgorithmId(kp, "SHA-512/256", NISTObjectIdentifiers.id_sha512_256);
    checkAlgorithmId(kp, "SHA-512(224)", NISTObjectIdentifiers.id_sha512_224);
    checkAlgorithmId(kp, "SHA-512(256)", NISTObjectIdentifiers.id_sha512_256);
}

28. AllTests#testEncryptedValue()

Project: bc-java
Source File: AllTests.java
View license
public void testEncryptedValue() throws Exception {
    KeyPairGenerator kGen = KeyPairGenerator.getInstance("RSA", BC);
    kGen.initialize(512);
    KeyPair kp = kGen.generateKeyPair();
    X509Certificate cert = makeV1Certificate(kp, "CN=Test", kp, "CN=Test");
    JcaEncryptedValueBuilder build = new JcaEncryptedValueBuilder(new JceAsymmetricKeyWrapper(cert.getPublicKey()).setProvider(BC), new JceCRMFEncryptorBuilder(CMSAlgorithm.AES128_CBC).setProvider(BC).build());
    EncryptedValue value = build.build(cert);
    ValueDecryptorGenerator decGen = new JceAsymmetricValueDecryptorGenerator(kp.getPrivate()).setProvider(BC);
    // try direct
    encryptedValueParserTest(value, decGen, cert);
    // try indirect
    encryptedValueParserTest(EncryptedValue.getInstance(value.getEncoded()), decGen, cert);
}

29. AllTests#testEncryptedValuePassphrase()

Project: bc-java
Source File: AllTests.java
View license
public void testEncryptedValuePassphrase() throws Exception {
    char[] passphrase = PASSPHRASE.toCharArray();
    KeyPairGenerator kGen = KeyPairGenerator.getInstance("RSA", BC);
    kGen.initialize(512);
    KeyPair kp = kGen.generateKeyPair();
    X509Certificate cert = makeV1Certificate(kp, "CN=Test", kp, "CN=Test");
    EncryptedValueBuilder build = new EncryptedValueBuilder(new JceAsymmetricKeyWrapper(cert.getPublicKey()).setProvider(BC), new JceCRMFEncryptorBuilder(CMSAlgorithm.AES128_CBC).setProvider(BC).build());
    EncryptedValue value = build.build(passphrase);
    ValueDecryptorGenerator decGen = new JceAsymmetricValueDecryptorGenerator(kp.getPrivate()).setProvider(BC);
    // try direct
    encryptedValuePassphraseParserTest(value, null, decGen, cert);
    // try indirect
    encryptedValuePassphraseParserTest(EncryptedValue.getInstance(value.getEncoded()), null, decGen, cert);
}

30. AllTests#testEncryptedValuePassphraseWithPadding()

Project: bc-java
Source File: AllTests.java
View license
public void testEncryptedValuePassphraseWithPadding() throws Exception {
    char[] passphrase = PASSPHRASE.toCharArray();
    KeyPairGenerator kGen = KeyPairGenerator.getInstance("RSA", BC);
    kGen.initialize(512);
    KeyPair kp = kGen.generateKeyPair();
    X509Certificate cert = makeV1Certificate(kp, "CN=Test", kp, "CN=Test");
    BcFixedLengthMGF1Padder mgf1Padder = new BcFixedLengthMGF1Padder(200, new SecureRandom());
    EncryptedValueBuilder build = new EncryptedValueBuilder(new JceAsymmetricKeyWrapper(cert.getPublicKey()).setProvider(BC), new JceCRMFEncryptorBuilder(CMSAlgorithm.AES128_CBC).setProvider(BC).build(), mgf1Padder);
    EncryptedValue value = build.build(passphrase);
    ValueDecryptorGenerator decGen = new JceAsymmetricValueDecryptorGenerator(kp.getPrivate()).setProvider(BC);
    // try direct
    encryptedValuePassphraseParserTest(value, mgf1Padder, decGen, cert);
    // try indirect
    encryptedValuePassphraseParserTest(EncryptedValue.getInstance(value.getEncoded()), mgf1Padder, decGen, cert);
}

31. ParserTest#doOpenSslTestFile()

Project: bc-java
Source File: ParserTest.java
View license
private void doOpenSslTestFile(String fileName, Class expectedPrivKeyClass) throws IOException {
    JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
    PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().setProvider("BC").build("changeit".toCharArray());
    PEMParser pr = openPEMResource("data/" + fileName);
    Object o = pr.readObject();
    if (o == null || !((o instanceof PEMKeyPair) || (o instanceof PEMEncryptedKeyPair))) {
        fail("Didn't find OpenSSL key");
    }
    KeyPair kp = (o instanceof PEMEncryptedKeyPair) ? converter.getKeyPair(((PEMEncryptedKeyPair) o).decryptKeyPair(decProv)) : converter.getKeyPair((PEMKeyPair) o);
    PrivateKey privKey = kp.getPrivate();
    if (!expectedPrivKeyClass.isInstance(privKey)) {
        fail("Returned key not of correct type");
    }
}

32. AllTests#testEncryptedValue()

Project: bc-java
Source File: AllTests.java
View license
public void testEncryptedValue() throws Exception {
    KeyPairGenerator kGen = KeyPairGenerator.getInstance("RSA", BC);
    kGen.initialize(512);
    KeyPair kp = kGen.generateKeyPair();
    X509Certificate cert = makeV1Certificate(kp, "CN=Test", kp, "CN=Test");
    JcaEncryptedValueBuilder build = new JcaEncryptedValueBuilder(new JceAsymmetricKeyWrapper(cert.getPublicKey()).setProvider(BC), new JceCRMFEncryptorBuilder(CMSAlgorithm.AES128_CBC).setProvider(BC).build());
    EncryptedValue value = build.build(cert);
    ValueDecryptorGenerator decGen = new JceAsymmetricValueDecryptorGenerator(kp.getPrivate()).setProvider(BC);
    // try direct
    encryptedValueParserTest(value, decGen, cert);
    // try indirect
    encryptedValueParserTest(EncryptedValue.getInstance(value.getEncoded()), decGen, cert);
}

33. AllTests#testEncryptedValuePassphrase()

Project: bc-java
Source File: AllTests.java
View license
public void testEncryptedValuePassphrase() throws Exception {
    char[] passphrase = PASSPHRASE.toCharArray();
    KeyPairGenerator kGen = KeyPairGenerator.getInstance("RSA", BC);
    kGen.initialize(512);
    KeyPair kp = kGen.generateKeyPair();
    X509Certificate cert = makeV1Certificate(kp, "CN=Test", kp, "CN=Test");
    EncryptedValueBuilder build = new EncryptedValueBuilder(new JceAsymmetricKeyWrapper(cert.getPublicKey()).setProvider(BC), new JceCRMFEncryptorBuilder(CMSAlgorithm.AES128_CBC).setProvider(BC).build());
    EncryptedValue value = build.build(passphrase);
    ValueDecryptorGenerator decGen = new JceAsymmetricValueDecryptorGenerator(kp.getPrivate()).setProvider(BC);
    // try direct
    encryptedValuePassphraseParserTest(value, null, decGen, cert);
    // try indirect
    encryptedValuePassphraseParserTest(EncryptedValue.getInstance(value.getEncoded()), null, decGen, cert);
}

34. AllTests#testEncryptedValuePassphraseWithPadding()

Project: bc-java
Source File: AllTests.java
View license
public void testEncryptedValuePassphraseWithPadding() throws Exception {
    char[] passphrase = PASSPHRASE.toCharArray();
    KeyPairGenerator kGen = KeyPairGenerator.getInstance("RSA", BC);
    kGen.initialize(512);
    KeyPair kp = kGen.generateKeyPair();
    X509Certificate cert = makeV1Certificate(kp, "CN=Test", kp, "CN=Test");
    BcFixedLengthMGF1Padder mgf1Padder = new BcFixedLengthMGF1Padder(200, new SecureRandom());
    EncryptedValueBuilder build = new EncryptedValueBuilder(new JceAsymmetricKeyWrapper(cert.getPublicKey()).setProvider(BC), new JceCRMFEncryptorBuilder(CMSAlgorithm.AES128_CBC).setProvider(BC).build(), mgf1Padder);
    EncryptedValue value = build.build(passphrase);
    ValueDecryptorGenerator decGen = new JceAsymmetricValueDecryptorGenerator(kp.getPrivate()).setProvider(BC);
    // try direct
    encryptedValuePassphraseParserTest(value, mgf1Padder, decGen, cert);
    // try indirect
    encryptedValuePassphraseParserTest(EncryptedValue.getInstance(value.getEncoded()), mgf1Padder, decGen, cert);
}

35. AllTests#testOaepWrap()

Project: bc-java
Source File: AllTests.java
View license
public void testOaepWrap() throws Exception {
    KeyPairGenerator kGen = KeyPairGenerator.getInstance("RSA", BC);
    kGen.initialize(2048);
    KeyPair kp = kGen.generateKeyPair();
    checkAlgorithmId(kp, "SHA-1", OIWObjectIdentifiers.idSHA1);
    checkAlgorithmId(kp, "SHA-224", NISTObjectIdentifiers.id_sha224);
    checkAlgorithmId(kp, "SHA-256", NISTObjectIdentifiers.id_sha256);
    checkAlgorithmId(kp, "SHA-384", NISTObjectIdentifiers.id_sha384);
    checkAlgorithmId(kp, "SHA-512", NISTObjectIdentifiers.id_sha512);
    checkAlgorithmId(kp, "SHA-512/224", NISTObjectIdentifiers.id_sha512_224);
    checkAlgorithmId(kp, "SHA-512/256", NISTObjectIdentifiers.id_sha512_256);
    checkAlgorithmId(kp, "SHA-512(224)", NISTObjectIdentifiers.id_sha512_224);
    checkAlgorithmId(kp, "SHA-512(256)", NISTObjectIdentifiers.id_sha512_256);
}

36. RSATest#zeroMessageTest()

Project: bc-java
Source File: RSATest.java
View license
public void zeroMessageTest() throws Exception {
    KeyPairGenerator kgen = KeyPairGenerator.getInstance("RSA", "BC");
    RSAKeyGenParameterSpec rsaSpec = new RSAKeyGenParameterSpec(2048, RSAKeyGenParameterSpec.F4);
    kgen.initialize(rsaSpec);
    KeyPair kp = kgen.generateKeyPair();
    byte[] plain = new byte[0];
    Cipher rsaCipher = Cipher.getInstance("RSA/NONE/OAEPWithSHA1AndMGF1Padding", "BC");
    rsaCipher.init(Cipher.ENCRYPT_MODE, kp.getPublic());
    byte[] encrypted = rsaCipher.doFinal(plain);
    rsaCipher = Cipher.getInstance("RSA/NONE/OAEPWithSHA1AndMGF1Padding", "BC");
    rsaCipher.init(Cipher.DECRYPT_MODE, kp.getPrivate());
    byte[] decrypted = rsaCipher.doFinal(encrypted);
    isTrue("zero mismatch", Arrays.areEqual(plain, decrypted));
}

37. Sphincs256Test#testSphincsSha2Signature()

Project: bc-java
Source File: Sphincs256Test.java
View license
public void testSphincsSha2Signature() throws Exception {
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("SPHINCS256", "BCPQC");
    kpg.initialize(new SPHINCS256KeyGenParameterSpec(SPHINCS256KeyGenParameterSpec.SHA512_256), new RiggedRandom());
    KeyPair kp = kpg.generateKeyPair();
    Signature sig = Signature.getInstance("SHA512withSPHINCS256", "BCPQC");
    sig.initSign(kp.getPrivate());
    sig.update(msg, 0, msg.length);
    byte[] s = sig.sign();
    assertTrue(Arrays.areEqual(expSha2Sig, s));
}

38. Sphincs256Test#testSphincsSha3Signature()

Project: bc-java
Source File: Sphincs256Test.java
View license
public void testSphincsSha3Signature() throws Exception {
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("SPHINCS256", "BCPQC");
    kpg.initialize(new SPHINCS256KeyGenParameterSpec(SPHINCS256KeyGenParameterSpec.SHA512_256), new RiggedRandom());
    KeyPair kp = kpg.generateKeyPair();
    Signature sig = Signature.getInstance("SHA3-512withSPHINCS256", "BCPQC");
    sig.initSign(kp.getPrivate());
    sig.update(msg, 0, msg.length);
    byte[] s = sig.sign();
    assertTrue(Arrays.areEqual(expSha3Sig, s));
}

39. Settings#generate()

Project: bnd
Source File: Settings.java
View license
public void generate(char[] password) throws Exception {
    check();
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    keyGen.initialize(1024, random);
    KeyPair pair = keyGen.generateKeyPair();
    privateKey = pair.getPrivate();
    publicKey = pair.getPublic();
    data.secret = privateKey.getEncoded();
    data.id = publicKey.getEncoded();
    save(password);
}

40. SignatureTests#testProvideKeysInHeader()

Project: camel
Source File: SignatureTests.java
View license
@Test
public void testProvideKeysInHeader() throws Exception {
    setupMock();
    Exchange unsigned = getMandatoryEndpoint("direct:headerkey-sign").createExchange();
    unsigned.getIn().setBody(payload);
    // create a keypair
    KeyPair pair = getKeyPair("DSA");
    // sign with the private key
    unsigned.getIn().setHeader(SIGNATURE_PRIVATE_KEY, pair.getPrivate());
    template.send("direct:headerkey-sign", unsigned);
    // verify with the public key
    Exchange signed = getMandatoryEndpoint("direct:alias-sign").createExchange();
    signed.getIn().copyFrom(unsigned.getOut());
    signed.getIn().setHeader(SIGNATURE_PUBLIC_KEY_OR_CERT, pair.getPublic());
    template.send("direct:headerkey-verify", signed);
    assertMockEndpointsSatisfied();
}

41. SftpKeyPairDSAConsumeTest#createRegistry()

View license
@Override
protected JndiRegistry createRegistry() throws Exception {
    JndiRegistry registry = super.createRegistry();
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");
    keyGen.initialize(1024);
    KeyPair pair = keyGen.generateKeyPair();
    registry.bind("keyPair", pair);
    registry.bind("knownHosts", getBytesFromFile("./src/test/resources/known_hosts"));
    return registry;
}

42. SftpKeyPairRSAConsumeTest#createRegistry()

View license
@Override
protected JndiRegistry createRegistry() throws Exception {
    JndiRegistry registry = super.createRegistry();
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(2048);
    KeyPair pair = keyGen.generateKeyPair();
    registry.bind("keyPair", pair);
    registry.bind("knownHosts", getBytesFromFile("./src/test/resources/known_hosts"));
    return registry;
}

43. HostApiRSAKeyProvider#getCACertificate()

Project: cattle
Source File: HostApiRSAKeyProvider.java
View license
protected X509Certificate getCACertificate() {
    final KeyPair kp = getKeyPair();
    String encoded = dataDao.getOrCreate(CERT, false, new Callable<String>() {

        @Override
        public String call() throws Exception {
            X509Certificate cert = SshKeyGen.createRootCACert(kp);
            return SshKeyGen.toPEM(cert);
        }
    });
    try {
        return SshKeyGen.readCACert(encoded);
    } catch (Exception e) {
        ExceptionUtils.throwRuntime("Failed to CA cert from PEM", e);
        return null;
    }
}

44. SampleApp#getKeyPair()

Project: ChatSecureAndroid
Source File: SampleApp.java
View license
@Override
public KeyPair getKeyPair(SessionID sessionID) {
    KeyPair kp = null;
    try {
        kp = otrKeyManager.loadLocalKeyPair(sessionID);
    } catch (NullPointerException ex) {
    }
    if (kp == null) {
        otrKeyManager.generateLocalKeyPair(sessionID);
        kp = otrKeyManager.loadLocalKeyPair(sessionID);
    }
    return kp;
}

45. OtrAndroidKeyManagerImpl#getLocalFingerprint()

View license
public String getLocalFingerprint(String fullUserId) {
    String userId = Address.stripResource(fullUserId);
    KeyPair keyPair = loadLocalKeyPair(userId);
    if (keyPair == null)
        return null;
    PublicKey pubKey = keyPair.getPublic();
    try {
        String fingerprint = cryptoEngine.getFingerprint(pubKey);
        //  OtrDebugLogger.log("got fingerprint for: " + userId + "=" + fingerprint);
        return fingerprint;
    } catch (OtrCryptoException e) {
        e.printStackTrace();
        return null;
    }
}

46. OtrKeyManagerDefaultImpl#getLocalFingerprint()

View license
public String getLocalFingerprint(SessionID sessionID) {
    KeyPair keyPair = loadLocalKeyPair(sessionID);
    if (keyPair == null)
        return null;
    PublicKey pubKey = keyPair.getPublic();
    try {
        return new OtrCryptoEngineImpl().getFingerprint(pubKey);
    } catch (OtrCryptoException e) {
        e.printStackTrace();
        return null;
    }
}

47. SessionImpl#rotateLocalSessionKeys()

Project: ChatSecureAndroid
Source File: SessionImpl.java
View license
private void rotateLocalSessionKeys() throws OtrException {
    if (Debug.DEBUG_ENABLED)
        Log.d(ImApp.LOG_TAG, "Rotating local keys.");
    SessionKeys sess1 = getSessionKeysByIndex(SessionKeys.Previous, SessionKeys.Current);
    if (sess1.getIsUsedReceivingMACKey()) {
        if (Debug.DEBUG_ENABLED)
            Log.d(ImApp.LOG_TAG, "Detected used Receiving MAC key. Adding to old MAC keys to reveal it.");
        getOldMacKeys().add(sess1.getReceivingMACKey());
    }
    SessionKeys sess2 = getSessionKeysByIndex(SessionKeys.Previous, SessionKeys.Previous);
    if (sess2.getIsUsedReceivingMACKey()) {
        if (Debug.DEBUG_ENABLED)
            Log.d(ImApp.LOG_TAG, "Detected used Receiving MAC key. Adding to old MAC keys to reveal it.");
        getOldMacKeys().add(sess2.getReceivingMACKey());
    }
    SessionKeys sess3 = getSessionKeysByIndex(SessionKeys.Current, SessionKeys.Current);
    sess1.setLocalPair(sess3.getLocalPair(), sess3.getLocalKeyID());
    SessionKeys sess4 = getSessionKeysByIndex(SessionKeys.Current, SessionKeys.Previous);
    sess2.setLocalPair(sess4.getLocalPair(), sess4.getLocalKeyID());
    KeyPair newPair = new OtrCryptoEngineImpl().generateDHKeyPair();
    sess3.setLocalPair(newPair, sess3.getLocalKeyID() + 1);
    sess4.setLocalPair(newPair, sess4.getLocalKeyID() + 1);
}

48. IOTest#testIOBigInt()

Project: ChatSecureAndroid
Source File: IOTest.java
View license
public void testIOBigInt() throws Exception {
    KeyPair pair = new OtrCryptoEngineImpl().generateDHKeyPair();
    BigInteger source = ((DHPublicKey) pair.getPublic()).getY();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    OtrOutputStream oos = new OtrOutputStream(out);
    oos.writeBigInt(source);
    oos.close();
    byte[] converted = out.toByteArray();
    ByteArrayInputStream bin = new ByteArrayInputStream(converted);
    OtrInputStream ois = new OtrInputStream(bin);
    BigInteger result = ois.readBigInt();
    ois.close();
    assertTrue(source.compareTo(result) == 0);
}

49. IOTest#testIODHPublicKey()

Project: ChatSecureAndroid
Source File: IOTest.java
View license
public void testIODHPublicKey() throws Exception {
    KeyPair pair = new OtrCryptoEngineImpl().generateDHKeyPair();
    DHPublicKey source = (DHPublicKey) pair.getPublic();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    OtrOutputStream oos = new OtrOutputStream(out);
    oos.writeDHPublicKey(source);
    oos.close();
    byte[] converted = out.toByteArray();
    ByteArrayInputStream bin = new ByteArrayInputStream(converted);
    OtrInputStream ois = new OtrInputStream(bin);
    DHPublicKey result = ois.readDHPublicKey();
    ois.close();
    assertTrue(source.getY().compareTo(result.getY()) == 0);
}

50. DefaultJSONSignerTests#generateRandomKeyPair()

Project: core
Source File: DefaultJSONSignerTests.java
View license
public KeyPair generateRandomKeyPair() {
    KeyPair keyPair = null;
    try {
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
        kpg.initialize(512);
        keyPair = kpg.genKeyPair();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return keyPair;
}

51. CertificateStore#getStoredKeyPair()

Project: core
Source File: CertificateStore.java
View license
public KeyPair getStoredKeyPair() throws CertificateException, KeyStoreException, IOException, UnrecoverableEntryException, NoSuchAlgorithmException {
    loadKeyStore();
    KeyPair keyPair = null;
    if (keyStore.containsAlias(alias)) {
        KeyStore.PrivateKeyEntry pke = (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias, new KeyStore.PasswordProtection(password));
        Certificate cert = keyStore.getCertificate(alias);
        keyPair = new KeyPair(cert.getPublicKey(), pke.getPrivateKey());
    }
    return keyPair;
}

52. KeyPairUtility#generateRandomKeyPair()

Project: core
Source File: KeyPairUtility.java
View license
public static KeyPair generateRandomKeyPair() {
    KeyPair keyPair = null;
    try {
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
        kpg.initialize(RSA_KEY_SIZE);
        keyPair = kpg.genKeyPair();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return keyPair;
}

53. CertificateStoreTests#testSave()

Project: core
Source File: CertificateStoreTests.java
View license
@Test
public void testSave() throws Exception {
    store.saveCertificate(keyPair, certificate);
    //store now contains certificate
    Assert.assertTrue(store.isCertificateStored());
    store = null;
    //Password used to be PASSWORD.toCharArray(), invalid for current constructor, change if needed.
    CertificateStore store2 = new CertificateStore(tempFile, PASSWORD);
    KeyPair savedKeyPair = store2.getStoredKeyPair();
    //store 2 should contain certificate
    Assert.assertTrue(store2.isCertificateStored());
    //check key pair
    Assert.assertNotNull(savedKeyPair.getPublic());
    Assert.assertTrue(keyPair.getPrivate().equals(savedKeyPair.getPrivate()));
    Assert.assertNotNull(store2.getStoredKeyPair());
    //the certificate should exist
    Assert.assertNotNull(store2.getCertificate());
}

54. CertificateStoreTests#generateRandomKeyPair()

Project: core
Source File: CertificateStoreTests.java
View license
private KeyPair generateRandomKeyPair() {
    KeyPair keyPair = null;
    try {
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
        kpg.initialize(512);
        keyPair = kpg.genKeyPair();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return keyPair;
}

55. TestConfigs#testCreateSSLSocketFactory()

Project: datacollector
Source File: TestConfigs.java
View license
@Test
public void testCreateSSLSocketFactory() throws Exception {
    // create trust store
    File testDir = new File("target", UUID.randomUUID().toString());
    Assert.assertTrue(testDir.mkdirs());
    KeyPair kp = SSLTestUtils.generateKeyPair();
    Certificate cert1 = SSLTestUtils.generateCertificate("CN=Cert1", kp, 30);
    String truststoreFile = new File(testDir, "truststore.jks").toString();
    SSLTestUtils.createTrustStore(truststoreFile, "password", "cert1", cert1);
    ForTestConfigs target = new ForTestConfigs(null);
    injectConfigsHttps(target, truststoreFile, "password", true);
    SSLSocketFactory factory = target.createSSLSocketFactory(getContext());
    Assert.assertNotNull(factory);
}

56. AccessTokenKdcTest#testSignedTokenWithABadKey()

View license
@Test
public void testSignedTokenWithABadKey() throws Exception {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    KeyPair keyPair = keyGen.generateKeyPair();
    prepareToken(getServerPrincipal(), ISSUER, keyPair.getPrivate(), null);
    try {
        performTest();
        Assert.fail("Failure expected on a bad key");
    } catch (Exception ex) {
        Assert.assertTrue(ex instanceof KrbException);
    }
}

57. AccessTokenKdcTest#testSignedEncryptedTokenBadSigningKey()

View license
@Test
public void testSignedEncryptedTokenBadSigningKey() throws Exception {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    KeyPair keyPair = keyGen.generateKeyPair();
    InputStream is = TokenKdcTestBase.class.getResourceAsStream("/oauth2.com_public_key.pem");
    PublicKey publicKey = PublicKeyReader.loadPublicKey(is);
    prepareToken(getServerPrincipal(), ISSUER, keyPair.getPrivate(), publicKey);
    try {
        performTest();
        Assert.fail("Failure expected on a bad key");
    } catch (Exception ex) {
        Assert.assertTrue(ex instanceof KrbException);
    }
}

58. IdentityTokenKdcTest#testSignedTokenWithABadKey()

View license
@Test
public void testSignedTokenWithABadKey() throws Exception {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    KeyPair keyPair = keyGen.generateKeyPair();
    prepareToken(getAudience("krbtgt"), ISSUER, keyPair.getPrivate(), null);
    try {
        performTest();
        Assert.fail("Failure expected on a bad key");
    } catch (Exception ex) {
        Assert.assertTrue(ex instanceof KrbException);
    }
}

59. IdentityTokenKdcTest#testSignedEncryptedTokenBadSigningKey()

View license
@Test
public void testSignedEncryptedTokenBadSigningKey() throws Exception {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    KeyPair keyPair = keyGen.generateKeyPair();
    InputStream is = TokenKdcTestBase.class.getResourceAsStream("/oauth2.com_public_key.pem");
    PublicKey publicKey = PublicKeyReader.loadPublicKey(is);
    prepareToken(getAudience("krbtgt"), ISSUER, keyPair.getPrivate(), publicKey);
    try {
        performTest();
        Assert.fail("Failure expected on a bad key");
    } catch (Exception ex) {
        Assert.assertTrue(ex instanceof KrbException);
    }
}

60. DiffieHellmanClient#init()

View license
public DHPublicKey init(DHParameterSpec dhParamSpec) throws Exception {
    dhParameterSpec = dhParamSpec;
    // The client creates its own DH key pair, using the DH parameters from above.
    KeyPairGenerator clientKpairGen = KeyPairGenerator.getInstance("DH");
    clientKpairGen.initialize(dhParamSpec);
    KeyPair clientKpair = clientKpairGen.generateKeyPair();
    // The client creates and initializes its DH KeyAgreement object.
    clientKeyAgree = KeyAgreement.getInstance("DH");
    clientKeyAgree.init(clientKpair.getPrivate());
    // The client encodes its public key, and sends it over to the server.
    return (DHPublicKey) clientKpair.getPublic();
}

61. TokenTest#testTokenWithECDSASignedJWT()

Project: directory-kerby
Source File: TokenTest.java
View license
@Test
@org.junit.Ignore
public // TODO: building error with openjdk8: NoSuchAlgorithm EC KeyPairGenerato..
void testTokenWithECDSASignedJWT() throws Exception {
    TokenEncoder tokenEncoder = KrbRuntime.getTokenProvider().createTokenEncoder();
    TokenDecoder tokenDecoder = KrbRuntime.getTokenProvider().createTokenDecoder();
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC");
    KeyPair keyPair = kpg.generateKeyPair();
    ((JwtTokenEncoder) tokenEncoder).setSignKey(keyPair.getPrivate());
    ((JwtTokenEncoder) tokenEncoder).setJwsAlgorithm(JWSAlgorithm.ES256);
    ((JwtTokenDecoder) tokenDecoder).setVerifyKey(keyPair.getPublic());
    setAudience((JwtTokenDecoder) tokenDecoder, auds);
    String tokenStr = tokenEncoder.encodeAsString(authToken);
    Assertions.assertThat(tokenStr).isNotNull();
    AuthToken token2 = tokenDecoder.decodeFromString(tokenStr);
    Assertions.assertThat(token2.getSubject()).isEqualTo(SUBJECT);
    Assertions.assertThat(token2.getIssuer()).isEqualTo(ISSUER);
}

62. TlsKeyGeneratorTest#testAll()

View license
/**
     * Test method for all methods in one.
     */
@Test
public void testAll() throws Exception {
    Entry entry = new DefaultEntry(schemaManager, new Dn(schemaManager));
    TlsKeyGenerator.addKeyPair(entry);
    LOG.debug("Entry: {}", entry);
    assertTrue(entry.contains(SchemaConstants.OBJECT_CLASS_AT, TlsKeyGenerator.TLS_KEY_INFO_OC));
    KeyPair keyPair = TlsKeyGenerator.getKeyPair(entry);
    assertNotNull(keyPair);
    X509Certificate cert = TlsKeyGenerator.getCertificate(entry);
    assertNotNull(cert);
}

63. PEMFiles#getKeyPair()

Project: eucalyptus
Source File: PEMFiles.java
View license
@Nullable
public static KeyPair getKeyPair(final byte[] o) {
    KeyPair keyPair = null;
    ByteArrayInputStream pemByteIn = new ByteArrayInputStream(o);
    try (PEMParser in = new PEMParser(new InputStreamReader(pemByteIn))) {
        final Object keyObj = in.readObject();
        if (keyObj instanceof PEMKeyPair) {
            final PEMKeyPair pemKeyPair = (PEMKeyPair) keyObj;
            if (pemKeyPair != null) {
                keyPair = new JcaPEMKeyConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME).getKeyPair(pemKeyPair);
            }
        } else if (keyObj instanceof PrivateKeyInfo) {
            final PrivateKeyInfo pKeyInfo = (PrivateKeyInfo) keyObj;
            final PrivateKey pKey = new JcaPEMKeyConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME).getPrivateKey(pKeyInfo);
            if (pKey != null) {
                keyPair = new KeyPair(null, pKey);
            }
        }
    } catch (IOException e) {
        LOG.error(e, e);
    }
    return keyPair;
}

64. KeyStoreGBean#generateKeyPair()

Project: geronimo
Source File: KeyStoreGBean.java
View license
public void generateKeyPair(String alias, String keyalg, Integer keysize, String sigalg, Integer validity, String cn, String ou, String o, String l, String st, String c) throws java.security.NoSuchAlgorithmException, java.security.KeyStoreException, java.security.SignatureException, java.security.InvalidKeyException, java.security.cert.CertificateException, java.io.IOException {
    KeyPairGenerator kpgen = KeyPairGenerator.getInstance(keyalg);
    kpgen.initialize(keysize.intValue());
    KeyPair keyPair = kpgen.generateKeyPair();
    X509Certificate cert = generateCert(keyPair.getPublic(), keyPair.getPrivate(), sigalg, validity.intValue(), cn, ou, o, l, st, c);
    keystore.setKeyEntry(alias, keyPair.getPrivate(), new String().toCharArray(), new Certificate[] { cert });
    saveKeyStore();
}

65. SshKeysDispatcherTest#testKeysAddCommand()

Project: gitblit
Source File: SshKeysDispatcherTest.java
View license
@Test
public void testKeysAddCommand() throws Exception {
    KeyPair kp = generator.generateKeyPair();
    SshKey key = new SshKey(kp.getPublic());
    testSshCommand("keys add --permission R", key.getRawData());
    List<SshKey> keys = getKeyManager().getKeys(username);
    assertEquals(String.format("There are %d keys!", keys.size()), 3, keys.size());
    assertEquals(AccessPermission.CLONE, keys.get(2).getPermission());
    String result = testSshCommand("keys ls -L");
    StringBuilder sb = new StringBuilder();
    for (SshKey sk : keys) {
        sb.append(sk.getRawData());
        sb.append('\n');
    }
    sb.setLength(sb.length() - 1);
    assertEquals(sb.toString(), result);
}

66. GoogleAuthLibraryCallCredentialsTests#serviceAccountToJwt()

View license
@Test
public void serviceAccountToJwt() throws Exception {
    KeyPair pair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
    ServiceAccountCredentials credentials = new ServiceAccountCredentials(null, "[email protected]", pair.getPrivate(), null, null) {

        @Override
        public AccessToken refreshAccessToken() {
            throw new AssertionError();
        }
    };
    GoogleAuthLibraryCallCredentials callCredentials = new GoogleAuthLibraryCallCredentials(credentials);
    callCredentials.applyRequestMetadata(method, attrs, executor, applier);
    assertEquals(1, runPendingRunnables());
    verify(applier).apply(headersCaptor.capture());
    Metadata headers = headersCaptor.getValue();
    String[] authorization = Iterables.toArray(headers.getAll(AUTHORIZATION), String.class);
    assertEquals(1, authorization.length);
    assertTrue(authorization[0], authorization[0].startsWith("Bearer "));
    // JWT is reasonably long. Normal tokens aren't.
    assertTrue(authorization[0], authorization[0].length() > 300);
}

67. GoogleAuthLibraryCallCredentialsTests#serviceAccountWithScopeNotToJwt()

View license
@Test
public void serviceAccountWithScopeNotToJwt() throws Exception {
    final AccessToken token = new AccessToken("allyourbase", new Date(Long.MAX_VALUE));
    KeyPair pair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
    ServiceAccountCredentials credentials = new ServiceAccountCredentials(null, "[email protected]", pair.getPrivate(), null, Arrays.asList("somescope")) {

        @Override
        public AccessToken refreshAccessToken() {
            return token;
        }
    };
    GoogleAuthLibraryCallCredentials callCredentials = new GoogleAuthLibraryCallCredentials(credentials);
    callCredentials.applyRequestMetadata(method, attrs, executor, applier);
    assertEquals(1, runPendingRunnables());
    verify(applier).apply(headersCaptor.capture());
    Metadata headers = headersCaptor.getValue();
    Iterable<String> authorization = headers.getAll(AUTHORIZATION);
    assertArrayEquals(new String[] { "Bearer allyourbase" }, Iterables.toArray(authorization, String.class));
}

68. KeyPairGen#genKeyPairBytes()

Project: heisenberg
Source File: KeyPairGen.java
View license
private static byte[][] genKeyPairBytes(int keySize) throws NoSuchAlgorithmException {
    byte[][] keyPairBytes = new byte[2][];
    KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
    gen.initialize(keySize, new SecureRandom());
    KeyPair pair = gen.generateKeyPair();
    keyPairBytes[0] = pair.getPrivate().getEncoded();
    keyPairBytes[1] = pair.getPublic().getEncoded();
    return keyPairBytes;
}

69. CreateMetaFileStep#doExecute()

Project: Hive2Hive
Source File: CreateMetaFileStep.java
View license
@Override
protected Void doExecute() throws InvalidProcessStateException {
    File file = context.consumeFile();
    KeyPair metaKeys = context.consumeMetaFileEncryptionKeys();
    BaseMetaFile metaFile = null;
    if (context.isLargeFile()) {
        metaFile = new MetaFileLarge(metaKeys.getPublic(), context.getMetaChunks());
    } else {
        // create new meta file with new version
        FileVersion version = new FileVersion(0, FileUtil.getFileSize(file), System.currentTimeMillis(), context.getMetaChunks());
        List<FileVersion> versions = new ArrayList<FileVersion>(1);
        versions.add(version);
        metaFile = new MetaFileSmall(metaKeys.getPublic(), versions, context.consumeChunkEncryptionKeys());
    }
    context.provideMetaFile(metaFile);
    setRequiresRollback(true);
    return null;
}

70. CleanupChunksStep#doExecute()

Project: Hive2Hive
Source File: CleanupChunksStep.java
View license
@Override
protected Void doExecute() throws InvalidProcessStateException, ProcessExecutionException {
    List<MetaChunk> chunksToDelete = context.getChunksToDelete();
    KeyPair protectionKeys = context.consumeChunkProtectionKeys();
    logger.debug("Cleaning {} old file chunks.", chunksToDelete.size());
    int counter = 0;
    IProcessComponent<?> prev = this;
    for (MetaChunk metaChunk : chunksToDelete) {
        logger.debug("Delete chunk {} of {}.", counter++, chunksToDelete.size());
        DeleteSingleChunkStep deleteStep = new DeleteSingleChunkStep(metaChunk.getChunkId(), protectionKeys, dataManager);
        // make async, insert it as next step
        IProcessComponent<?> asyncDeletion = new AsyncComponent<>(deleteStep);
        getParent().insertAfter(asyncDeletion, prev);
        prev = asyncDeletion;
    }
    return null;
}

71. FileSynchronizerTest#testAddedRemotely()

Project: Hive2Hive
Source File: FileSynchronizerTest.java
View license
@Test
public void testAddedRemotely() throws IOException, ClassNotFoundException {
    KeyPair keys = generateRSAKeyPair(H2HConstants.KEYLENGTH_META_FILE);
    Index node1f3 = new FileIndex(root, keys, "1f3", null);
    Index node2d2 = new FolderIndex(node1d, keys, "2d2");
    Map<String, byte[]> same = FileSynchronizer.visitFiles(rootFile);
    FileSynchronizer fileSynchronizer = new FileSynchronizer(rootFile, userProfile, same, same);
    List<Index> addedRemotely = fileSynchronizer.getAddedRemotely();
    Assert.assertEquals(2, addedRemotely.size());
    Assert.assertTrue(addedRemotely.contains(node1f3));
    Assert.assertTrue(addedRemotely.contains(node2d2));
}

72. AESEncryptedVersionManagerTest#testContentProtectionPutWithWrongProtectionKey()

View license
@Test(expected = PutFailedException.class)
public void testContentProtectionPutWithWrongProtectionKey() throws Exception {
    NetworkManager node = NetworkTestUtil.getRandomNode(network);
    String locationKey = randomString();
    String contentKey = randomString();
    AESEncryptedVersionManager<H2HTestData> versionManager = new AESEncryptedVersionManager<H2HTestData>(node.getDataManager(), encryptionKey, locationKey, contentKey);
    KeyPair otherProtectionKeys = generateRSAKeyPair(H2HConstants.KEYLENGTH_PROTECTION);
    H2HTestData version0 = new H2HTestData("version0");
    versionManager.put(version0, protectionKeys);
    H2HTestData version1 = new H2HTestData("version1");
    version1.setVersionKey(version0.getVersionKey());
    versionManager.put(version1, otherProtectionKeys);
}

73. VersionManagerTest#testContentProtectionPutWithWrongProtectionKey()

Project: Hive2Hive
Source File: VersionManagerTest.java
View license
@Test(expected = PutFailedException.class)
public void testContentProtectionPutWithWrongProtectionKey() throws Exception {
    NetworkManager node = NetworkTestUtil.getRandomNode(network);
    String locationKey = randomString();
    String contentKey = randomString();
    VersionManager<H2HTestData> versionManager = new VersionManager<H2HTestData>(node.getDataManager(), locationKey, contentKey);
    KeyPair otherProtectionKeys = generateRSAKeyPair(H2HConstants.KEYLENGTH_PROTECTION);
    H2HTestData version0 = new H2HTestData("version0");
    versionManager.put(version0, protectionKeys);
    H2HTestData version1 = new H2HTestData("version1");
    version1.setVersionKey(version0.getVersionKey());
    versionManager.put(version1, otherProtectionKeys);
}

74. UserProfileTaskQueueTest#testPut()

View license
@Test
public void testPut() throws NoPeerConnectionException, InvalidProcessStateException, ProcessRollbackException {
    UserCredentials credentials = generateRandomCredentials();
    TestUserProfileTask userProfileTask = new TestUserProfileTask(generateRSAKeyPair(H2HConstants.KEYLENGTH_PROTECTION));
    KeyPair key = generateRSAKeyPair(H2HConstants.KEYLENGTH_USER_KEYS);
    NetworkManager node = NetworkTestUtil.getRandomNode(network);
    TestPutUserProfileTaskStep putStep = new TestPutUserProfileTaskStep(credentials.getUserId(), userProfileTask, key.getPublic(), node);
    TestExecutionUtil.executeProcessTillSucceded(putStep);
    // check if user profile task has been put into network
    Parameters parameters = new Parameters().setLocationKey(credentials.getUserId()).setDomainKey(H2HConstants.USER_PROFILE_TASK_DOMAIN).setContentKey(userProfileTask.getContentKey());
    assertNotNull(node.getDataManager().get(parameters));
    // manually trigger roll back
    putStep.rollback();
    // check if user profile task has been removed from network
    assertNull(node.getDataManager().get(parameters));
}

75. AddFileTest#verifyUpload()

Project: Hive2Hive
Source File: AddFileTest.java
View license
private void verifyUpload(File originalFile, int expectedChunks) throws IOException, GetFailedException, NoSessionException, NoPeerConnectionException, InvalidProcessStateException, ProcessExecutionException {
    // pick new client to test
    NetworkManager client = network.get(1);
    // test if there is something in the user profile
    UserProfile gotProfile = UseCaseTestUtil.getUserProfile(client, userCredentials);
    Assert.assertNotNull(gotProfile);
    Index node = gotProfile.getFileByPath(originalFile, uploaderRoot);
    Assert.assertNotNull(node);
    // verify the meta document
    KeyPair metaFileKeys = node.getFileKeys();
    if (originalFile.isFile()) {
        BaseMetaFile metaFile = UseCaseTestUtil.getMetaFile(client, metaFileKeys);
        Assert.assertNotNull(metaFile);
        Assert.assertTrue(metaFile instanceof MetaFileSmall);
        MetaFileSmall metaFileSmall = (MetaFileSmall) metaFile;
        // get the meta file with the keys (decrypt it)
        Assert.assertEquals(1, metaFileSmall.getVersions().size());
        Assert.assertEquals(expectedChunks, metaFileSmall.getVersions().get(0).getMetaChunks().size());
    }
}

76. DeleteFileTest#testDeleteFolder()

Project: Hive2Hive
Source File: DeleteFileTest.java
View license
@Test
public void testDeleteFolder() throws FileNotFoundException, IllegalArgumentException, GetFailedException, InterruptedException, NoSessionException, NoPeerConnectionException {
    // add a folder to the network
    File folder = new File(root, randomString());
    folder.mkdir();
    UseCaseTestUtil.uploadNewFile(client, folder);
    // store some keys before deletion
    UserProfile userProfileBeforeDeletion = UseCaseTestUtil.getUserProfile(client, userCredentials);
    KeyPair metaKeyPair = userProfileBeforeDeletion.getFileByPath(folder, root).getFileKeys();
    // delete the folder
    UseCaseTestUtil.deleteFile(client, folder);
    // check if the folder is still in the DHT
    UserProfile userProfile = UseCaseTestUtil.getUserProfile(client, userCredentials);
    Assert.assertNull(userProfile.getFileById(metaKeyPair.getPublic()));
}

77. GenerateKeypair#main()

Project: jdk7u-jdk
Source File: GenerateKeypair.java
View license
public static void main(String[] args) throws Exception {
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA");
    kpg.initialize(512);
    // test generateKeyPair
    KeyPair kpair = kpg.generateKeyPair();
    if (kpair == null) {
        throw new Exception("no keypair generated");
    }
    // test genKeyPair
    kpair = kpg.genKeyPair();
    if (kpair == null) {
        throw new Exception("no keypair generated");
    }
}

78. GenerateRSAKeyPair#main()

Project: jdk7u-jdk
Source File: GenerateRSAKeyPair.java
View license
public static void main(String[] args) throws Exception {
    RSAKeyGenParameterSpec rsaSpec = new RSAKeyGenParameterSpec(1024, RSAKeyGenParameterSpec.F4);
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "SunRsaSign");
    kpg.initialize(rsaSpec);
    // test generateKeyPair
    KeyPair kpair = kpg.generateKeyPair();
    if (kpair == null) {
        throw new Exception("no keypair generated");
    }
}

79. MessageEncoderDecoderTest#generateKeys()

Project: kaa
Source File: MessageEncoderDecoderTest.java
View license
@Before
public void generateKeys() throws NoSuchAlgorithmException {
    KeyPairGenerator clientKeyGen = KeyPairGenerator.getInstance("RSA");
    clientKeyGen.initialize(2048);
    KeyPair kp = clientKeyGen.genKeyPair();
    clientPublic = kp.getPublic();
    clientPrivate = kp.getPrivate();
    KeyPairGenerator serverKeyGen = KeyPairGenerator.getInstance("RSA");
    serverKeyGen.initialize(2048);
    kp = serverKeyGen.genKeyPair();
    serverPublic = kp.getPublic();
    serverPrivate = kp.getPrivate();
    KeyPairGenerator otherKeyGen = KeyPairGenerator.getInstance("RSA");
    otherKeyGen.initialize(2048);
    kp = otherKeyGen.genKeyPair();
    theifPublic = kp.getPublic();
    theifPrivate = kp.getPrivate();
}

80. BootstrapTransportServiceTest#messageHandlerProcessTest()

View license
@Test
public void messageHandlerProcessTest() {
    BootstrapTransportService bService = new BootstrapTransportService();
    KeyStoreService keyStoreService = mock(KeyStoreService.class);
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    PublicKey publicKey = keyPair.getPublic();
    PrivateKey privateKey = keyPair.getPrivate();
    when(keyStoreService.getPublicKey()).thenReturn(publicKey);
    when(keyStoreService.getPrivateKey()).thenReturn(privateKey);
    ReflectionTestUtils.setField(bService, "supportUnencryptedConnection", true);
    ReflectionTestUtils.setField(bService, "bootstrapKeyStoreService", keyStoreService);
    ReflectionTestUtils.setField(bService, "properties", new Properties());
    bService.lookupAndInit();
    MessageHandler handler = (BootstrapTransportService.BootstrapMessageHandler) ReflectionTestUtils.getField(bService, "handler");
    SessionInitMessage encryptedSessionInitMessage = mockForSessionInitMessage(true);
    SessionInitMessage nonEncryptedSessionInitMessage = mockForSessionInitMessage(false);
    handler.process(encryptedSessionInitMessage);
    handler.process(nonEncryptedSessionInitMessage);
    verify(encryptedSessionInitMessage, timeout(1000)).getEncodedMessageData();
    verify(nonEncryptedSessionInitMessage, timeout(1000)).getEncodedMessageData();
}

81. TestCluster#buildBootstrapNodeInfo()

Project: kaa
Source File: TestCluster.java
View license
/**
     * Builds the bootstrap node info.
     *
     * @return the bootstrap node info
     * @throws NoSuchAlgorithmException the no such algorithm exception
     */
private static BootstrapNodeInfo buildBootstrapNodeInfo() throws NoSuchAlgorithmException {
    BootstrapNodeInfo nodeInfo = new BootstrapNodeInfo();
    KeyPair keys = KeyUtil.generateKeyPair();
    X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keys.getPublic().getEncoded());
    ByteBuffer testKeyData = ByteBuffer.wrap(x509EncodedKeySpec.getEncoded());
    nodeInfo.setConnectionInfo(new ConnectionInfo(BOOTSTRAP_NODE_HOST, 10090, testKeyData));
    nodeInfo.setTimeStarted(System.currentTimeMillis());
    nodeInfo.setTransports(new ArrayList<TransportMetaData>());
    return nodeInfo;
}

82. SkeletonKeyTokenTest#testRSA()

Project: keycloak
Source File: SkeletonKeyTokenTest.java
View license
@Test
public void testRSA() throws Exception {
    AccessToken token = createSimpleToken();
    token.id("111");
    token.addAccess("foo").addRole("admin");
    token.addAccess("bar").addRole("user");
    KeyPair keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
    String encoded = new JWSBuilder().jsonContent(token).rsa256(keyPair.getPrivate());
    JWSInput input = new JWSInput(encoded);
    token = input.readJsonContent(AccessToken.class);
    Assert.assertEquals("111", token.getId());
    Assert.assertTrue(RSAProvider.verify(input, keyPair.getPublic()));
}

83. XMLSignatureUtil#sign()

Project: keycloak
Source File: XMLSignatureUtil.java
View license
/**
     * Sign the root element
     *
     *
     * @return
     *
     * @throws GeneralSecurityException
     * @throws XMLSignatureException
     * @throws MarshalException
     */
public static Document sign(SignatureUtilTransferObject dto, String canonicalizationMethodType) throws GeneralSecurityException, MarshalException, XMLSignatureException {
    Document doc = dto.getDocumentToBeSigned();
    KeyPair keyPair = dto.getKeyPair();
    Node nextSibling = dto.getNextSibling();
    String digestMethod = dto.getDigestMethod();
    String referenceURI = dto.getReferenceURI();
    String signatureMethod = dto.getSignatureMethod();
    logger.trace("Document to be signed=" + DocumentUtil.asString(doc));
    PrivateKey signingKey = keyPair.getPrivate();
    PublicKey publicKey = keyPair.getPublic();
    DOMSignContext dsc = new DOMSignContext(signingKey, doc.getDocumentElement(), nextSibling);
    signImpl(dsc, digestMethod, signatureMethod, referenceURI, publicKey, dto.getX509Certificate(), canonicalizationMethodType);
    return doc;
}

84. KeycloakModelUtils#generateRealmKeys()

Project: keycloak
Source File: KeycloakModelUtils.java
View license
public static void generateRealmKeys(RealmModel realm) {
    KeyPair keyPair = null;
    try {
        KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
        generator.initialize(2048);
        keyPair = generator.generateKeyPair();
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
    realm.setPrivateKey(keyPair.getPrivate());
    realm.setPublicKey(keyPair.getPublic());
    X509Certificate certificate = null;
    try {
        certificate = CertificateUtils.generateV1SelfSignedCertificate(keyPair, realm.getName());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    realm.setCertificate(certificate);
    realm.setCodeSecret(generateCodeSecret());
}

85. KeycloakModelUtils#generateKeyPairCertificate()

Project: keycloak
Source File: KeycloakModelUtils.java
View license
public static CertificateRepresentation generateKeyPairCertificate(String subject) {
    KeyPair keyPair = null;
    try {
        KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
        generator.initialize(2048);
        keyPair = generator.generateKeyPair();
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
    X509Certificate certificate = null;
    try {
        certificate = CertificateUtils.generateV1SelfSignedCertificate(keyPair, subject);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    String privateKeyPem = KeycloakModelUtils.getPemFromKey(keyPair.getPrivate());
    String certPem = KeycloakModelUtils.getPemFromCertificate(certificate);
    CertificateRepresentation rep = new CertificateRepresentation();
    rep.setPrivateKey(privateKeyPem);
    rep.setCertificate(certPem);
    return rep;
}

86. RealmManager#generateKeys()

Project: keycloak
Source File: RealmManager.java
View license
public void generateKeys() {
    RealmRepresentation rep = realm.toRepresentation();
    KeyPair keyPair;
    try {
        KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
        generator.initialize(2048);
        keyPair = generator.generateKeyPair();
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
    rep.setPrivateKey(Base64.encodeBytes(keyPair.getPrivate().getEncoded()));
    rep.setPublicKey(Base64.encodeBytes(keyPair.getPublic().getEncoded()));
    X509Certificate certificate;
    try {
        certificate = CertificateUtils.generateV1SelfSignedCertificate(keyPair, rep.getId());
        rep.setCertificate(Base64.encodeBytes(certificate.getEncoded()));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    rep.setCodeSecret(org.keycloak.models.utils.KeycloakModelUtils.generateCodeSecret());
    realm.update(rep);
}

87. AbstractKeyPairProvider#loadKey()

View license
@Override
public KeyPair loadKey(String type) {
    ValidateUtils.checkNotNullAndNotEmpty(type, "No key type to load");
    Iterable<KeyPair> keys = loadKeys();
    for (KeyPair key : keys) {
        String keyType = KeyUtils.getKeyType(key);
        if (type.equals(keyType)) {
            return key;
        }
    }
    return null;
}

88. AbstractKeyPairProvider#getKeyTypes()

View license
@Override
public List<String> getKeyTypes() {
    List<String> types = new ArrayList<>();
    Iterable<KeyPair> keys = loadKeys();
    for (KeyPair key : keys) {
        String type = KeyUtils.getKeyType(key);
        if (GenericUtils.isEmpty(type) || types.contains(type)) {
            continue;
        }
        types.add(type);
    }
    return types;
}

89. MappedKeyPairProvider#mapUniquePairs()

View license
public static Map<String, KeyPair> mapUniquePairs(Collection<? extends KeyPair> pairs) {
    if (GenericUtils.isEmpty(pairs)) {
        return Collections.emptyMap();
    }
    Map<String, KeyPair> pairsMap = new TreeMap<String, KeyPair>(String.CASE_INSENSITIVE_ORDER);
    for (KeyPair kp : pairs) {
        String keyType = ValidateUtils.checkNotNullAndNotEmpty(KeyUtils.getKeyType(kp), "Cannot determine key type");
        KeyPair prev = pairsMap.put(keyType, kp);
        ValidateUtils.checkTrue(prev == null, "Multiple keys of type=%s", keyType);
    }
    return pairsMap;
}

90. AbstractGeneratorHostKeyProvider#clearLoadedKeys()

View license
public void clearLoadedKeys() {
    KeyPair kp;
    synchronized (keyPairHolder) {
        kp = keyPairHolder.getAndSet(null);
    }
    if ((kp != null) & log.isDebugEnabled()) {
        PublicKey key = kp.getPublic();
        log.debug("clearLoadedKeys({}) removed key={}-{}", getPath(), KeyUtils.getKeyType(key), KeyUtils.getFingerPrint(key));
    }
}

91. ClientTest#testPublicKeyAuthNewWithFailureOnFirstIdentity()

Project: mina-sshd
Source File: ClientTest.java
View license
@Test
public void testPublicKeyAuthNewWithFailureOnFirstIdentity() throws Exception {
    SimpleGeneratorHostKeyProvider provider = new SimpleGeneratorHostKeyProvider();
    provider.setAlgorithm(KeyUtils.RSA_ALGORITHM);
    final KeyPair pair = createTestHostKeyProvider().loadKey(KeyPairProvider.SSH_RSA);
    sshd.setPublickeyAuthenticator(new PublickeyAuthenticator() {

        @Override
        public boolean authenticate(String username, PublicKey key, ServerSession session) {
            return key.equals(pair.getPublic());
        }
    });
    client.setUserAuthFactories(Arrays.<NamedFactory<UserAuth>>asList(UserAuthPublicKeyFactory.INSTANCE));
    client.start();
    try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) {
        assertNotNull("Client session creation not signalled", clientSessionHolder.get());
        session.addPublicKeyIdentity(provider.loadKey(KeyPairProvider.SSH_RSA));
        session.addPublicKeyIdentity(pair);
        session.auth().verify(5L, TimeUnit.SECONDS);
    } finally {
        client.stop();
    }
    assertNull("Session closure not signalled", clientSessionHolder.get());
}

92. SimpleSessionClientTest#testLoginSessionWithIdentity()

View license
@Test
public void testLoginSessionWithIdentity() throws Exception {
    final KeyPair identity = Utils.getFirstKeyPair(createTestHostKeyProvider());
    final AtomicBoolean identityQueried = new AtomicBoolean(false);
    sshd.setPublickeyAuthenticator(new PublickeyAuthenticator() {

        @Override
        public boolean authenticate(String username, PublicKey key, ServerSession session) {
            if (username.equals(getCurrentTestName())) {
                identityQueried.set(true);
                return KeyUtils.compareKeys(identity.getPublic(), key);
            }
            return false;
        }
    });
    // make sure authentication occurs only with public keys
    sshd.setPasswordAuthenticator(RejectAllPasswordAuthenticator.INSTANCE);
    client.start();
    try (ClientSession session = simple.sessionLogin(TEST_LOCALHOST, port, getCurrentTestName(), identity)) {
        assertEquals("Mismatched session username", getCurrentTestName(), session.getUsername());
        assertTrue("User identity not queried", identityQueried.get());
    }
}

93. PEMGeneratorHostKeyProviderTest#validateKeyPairProvider()

View license
private static KeyPair validateKeyPairProvider(KeyPairProvider provider, String keyType) {
    Iterable<String> types = provider.getKeyTypes();
    KeyPair kp = null;
    for (String type : types) {
        if (keyType.equals(type)) {
            kp = provider.loadKey(keyType);
            assertNotNull("Failed to load key for " + keyType, kp);
            break;
        }
    }
    assertNotNull("Expected key type not found: " + keyType, kp);
    return kp;
}

94. SimpleGeneratorHostKeyProviderTest#validateKeyPairProvider()

View license
private static KeyPair validateKeyPairProvider(KeyPairProvider provider, String keyType) {
    Iterable<String> types = provider.getKeyTypes();
    KeyPair kp = null;
    for (String type : types) {
        if (keyType.equals(type)) {
            kp = provider.loadKey(keyType);
            assertNotNull("Failed to load key for " + keyType, kp);
            break;
        }
    }
    assertNotNull("Expected key type not found: " + keyType, kp);
    return kp;
}

95. DecryptUtil#genKeyPairBytes()

Project: Mycat-Server
Source File: DecryptUtil.java
View license
public static byte[][] genKeyPairBytes(int keySize) throws NoSuchAlgorithmException {
    byte[][] keyPairBytes = new byte[2][];
    KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
    gen.initialize(keySize, new SecureRandom());
    KeyPair pair = gen.generateKeyPair();
    keyPairBytes[0] = pair.getPrivate().getEncoded();
    keyPairBytes[1] = pair.getPublic().getEncoded();
    return keyPairBytes;
}

96. EncryptUtil#generateRSAKeyPair()

Project: NonViewUtils
Source File: EncryptUtil.java
View license
//--------------------------------
//RSA ?????
/**
     * ???????????????????
     *
     * @param keySize ????1024/2048 ?????1024
     * @return KeyPair ?????
     */
public static KeyPair generateRSAKeyPair(int keySize) {
    KeyPair ret = null;
    try {
        //1.????
        KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
        //2.??????????
        generator.initialize(keySize);
        //3.???????
        ret = generator.generateKeyPair();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return ret;
}

97. GenerateKeypair#main()

Project: openjdk
Source File: GenerateKeypair.java
View license
public static void main(String[] args) throws Exception {
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA");
    kpg.initialize(512);
    // test generateKeyPair
    KeyPair kpair = kpg.generateKeyPair();
    if (kpair == null) {
        throw new Exception("no keypair generated");
    }
    // test genKeyPair
    kpair = kpg.genKeyPair();
    if (kpair == null) {
        throw new Exception("no keypair generated");
    }
}

98. GenerateRSAKeyPair#main()

Project: openjdk
Source File: GenerateRSAKeyPair.java
View license
public static void main(String[] args) throws Exception {
    RSAKeyGenParameterSpec rsaSpec = new RSAKeyGenParameterSpec(1024, RSAKeyGenParameterSpec.F4);
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "SunRsaSign");
    kpg.initialize(rsaSpec);
    // test generateKeyPair
    KeyPair kpair = kpg.generateKeyPair();
    if (kpair == null) {
        throw new Exception("no keypair generated");
    }
}

99. VerifyRangeCheckOverflow#main()

View license
public static void main(String[] args) throws Exception {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("DSA");
    keyPairGenerator.initialize(1024);
    KeyPair keys = keyPairGenerator.generateKeyPair();
    PublicKey publicKey = keys.getPublic();
    byte[] sigBytes = new byte[100];
    Signature signature = Signature.getInstance("SHA1withDSA");
    signature.initVerify(publicKey);
    try {
        signature.verify(sigBytes, Integer.MAX_VALUE, 1);
    } catch (IllegalArgumentException ex) {
    }
}

100. SSLSocketFactoryFactory#generateCA()

View license
private void generateCA(X500Principal caName) throws GeneralSecurityException, IOException, OperatorCreationException {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(1024);
    KeyPair caPair = keyGen.generateKeyPair();
    caKey = caPair.getPrivate();
    PublicKey caPubKey = caPair.getPublic();
    Date begin = new Date();
    begin.setTime(begin.getTime() - DEFAULT_AGE);
    Date ends = new Date(begin.getTime() + DEFAULT_VALIDITY);
    X509Certificate cert = SunCertificateUtils.sign(caName, caPubKey, caName, caPubKey, caKey, begin, ends, BigInteger.ONE, null);
    caCerts = new X509Certificate[] { cert };
    keystore.setKeyEntry(CA, caKey, password, caCerts);
    saveKeystore();
}