List of usage examples for java.security KeyPair KeyPair
public KeyPair(PublicKey publicKey, PrivateKey privateKey)
From source file:net.nicholaswilliams.java.licensing.licensor.interfaces.cli.TestConsoleRSAKeyPairGenerator.java
@Test public void testDoCommandLine04() throws Exception { ByteArrayOutputStream stream = new ByteArrayOutputStream(); this.console.cli = EasyMock.createMockBuilder(CommandLine.class).withConstructor() .addMockedMethod("hasOption", String.class).addMockedMethod("getOptionValue", String.class) .createMock();/*from w w w. j a v a2s . c o m*/ PrivateKey privateKey = EasyMock.createMock(PrivateKey.class); PublicKey publicKey = EasyMock.createMock(PublicKey.class); KeyPair keyPair = new KeyPair(publicKey, privateKey); EasyMock.expect(this.console.cli.hasOption("classes")).andReturn(true); EasyMock.expect(this.console.cli.hasOption("privatePassword")).andReturn(true); EasyMock.expect(this.console.cli.getOptionValue("password")).andReturn("publicPassword04"); EasyMock.expect(this.console.cli.getOptionValue("privatePassword")).andReturn("privatePassword04"); EasyMock.expect(this.console.cli.getOptionValue("public")).andReturn("PublicKey02"); EasyMock.expect(this.console.cli.getOptionValue("publicPackage")).andReturn("com.example.licensing.public"); EasyMock.expect(this.console.cli.getOptionValue("private")).andReturn("PrivateKey02"); EasyMock.expect(this.console.cli.getOptionValue("privatePackage")) .andReturn("com.example.licensing.private"); EasyMock.expect(this.console.cli.getOptionValue("passwordClass")).andReturn("PublicPassword02"); EasyMock.expect(this.console.cli.getOptionValue("passwordPackage")) .andReturn("com.example.licensing.public"); EasyMock.expect(this.console.cli.getOptionValue("privatePasswordClass")).andReturn("PrivatePassword02"); EasyMock.expect(this.console.cli.getOptionValue("privatePasswordPackage")) .andReturn("com.example.licensing.private"); this.device.printOut("Generating RSA key pair, 2048-bit long modulus"); EasyMock.expectLastCall(); EasyMock.expect(this.device.out()).andReturn(new PrintStream(stream)); EasyMock.expect(this.generator.generateKeyPair()).andReturn(keyPair); this.device.printOutLn("+++"); EasyMock.expectLastCall(); this.device.printOutLn(); EasyMock.expectLastCall(); this.device.printOut("Key pair generated. Encrypting keys with 128-bit AES security"); EasyMock.expectLastCall(); EasyMock.expect(this.device.out()).andReturn(new PrintStream(stream)); final Capture<GeneratedClassDescriptor> descriptorA01 = new Capture<GeneratedClassDescriptor>(); final Capture<GeneratedClassDescriptor> descriptorA02 = new Capture<GeneratedClassDescriptor>(); final Capture<GeneratedClassDescriptor> descriptorB01 = new Capture<GeneratedClassDescriptor>(); final Capture<GeneratedClassDescriptor> descriptorB02 = new Capture<GeneratedClassDescriptor>(); final Capture<char[]> passwordA01 = new Capture<char[]>(); final Capture<char[]> passwordA02 = new Capture<char[]>(); final Capture<char[]> passwordB01 = new Capture<char[]>(); final Capture<char[]> passwordB02 = new Capture<char[]>(); this.generator.saveKeyPairToProviders(EasyMock.eq(keyPair), EasyMock.capture(descriptorA01), EasyMock.capture(descriptorA02), EasyMock.capture(passwordA01), EasyMock.capture(passwordA02)); EasyMock.expectLastCall().andAnswer(new IAnswer<Void>() { @Override public Void answer() throws Throwable { assertNotNull("The private key password should not be null.", passwordA01.getValue()); assertArrayEquals("The private key password is not correct.", "privatePassword04".toCharArray(), passwordA01.getValue()); assertNotNull("The public key password should not be null.", passwordA02.getValue()); assertArrayEquals("The public key password is not correct.", "publicPassword04".toCharArray(), passwordA02.getValue()); descriptorA01.getValue().setJavaFileContents("privateKeyContents02"); descriptorA02.getValue().setJavaFileContents("publicKeyContents02"); return null; } }); this.generator.savePasswordToProvider(EasyMock.capture(passwordB01), EasyMock.capture(descriptorB01)); EasyMock.expectLastCall().andAnswer(new IAnswer<Void>() { @Override public Void answer() throws Throwable { assertNotNull("The public key password should still not be null.", passwordB01.getValue()); assertArrayEquals("The public key password is now not correct.", "publicPassword04".toCharArray(), passwordB01.getValue()); descriptorB01.getValue().setJavaFileContents("publicPasswordContents02"); return null; } }); this.generator.savePasswordToProvider(EasyMock.capture(passwordB02), EasyMock.capture(descriptorB02)); EasyMock.expectLastCall().andAnswer(new IAnswer<Void>() { @Override public Void answer() throws Throwable { assertNotNull("The private key password should still not be null.", passwordB02.getValue()); assertArrayEquals("The private key password is now not correct.", "privatePassword04".toCharArray(), passwordB02.getValue()); descriptorB02.getValue().setJavaFileContents("privatePasswordContents02"); return null; } }); this.device.printOutLn("+++"); EasyMock.expectLastCall(); this.device.printOutLn(); EasyMock.expectLastCall(); this.device.printOutLn("Private key provider:"); EasyMock.expectLastCall(); this.device.printOutLn(); EasyMock.expectLastCall(); this.device.printOutLn("privateKeyContents02"); EasyMock.expectLastCall(); this.device.printOutLn(); EasyMock.expectLastCall(); this.device.printOutLn("Public key provider:"); EasyMock.expectLastCall(); this.device.printOutLn(); EasyMock.expectLastCall(); this.device.printOutLn("publicKeyContents02"); EasyMock.expectLastCall(); this.device.printOutLn(); EasyMock.expectLastCall(); this.device.printOutLn("Public key password provider:"); EasyMock.expectLastCall(); this.device.printOutLn(); EasyMock.expectLastCall(); this.device.printOutLn("publicPasswordContents02"); EasyMock.expectLastCall(); this.device.printOutLn(); EasyMock.expectLastCall(); this.device.printOutLn("Private key password provider:"); EasyMock.expectLastCall(); this.device.printOutLn(); EasyMock.expectLastCall(); this.device.printOutLn("privatePasswordContents02"); EasyMock.expectLastCall(); EasyMock.replay(this.generator, this.device, this.console.cli, privateKey, publicKey); try { this.console.doCommandLine(); assertNotNull("The public key password should again still not be null.", passwordA01.getValue()); assertArrayEquals("The public key password should have been erased.", new char[passwordA01.getValue().length], passwordA01.getValue()); assertNotNull("The private key password should again still not be null.", passwordA02.getValue()); assertArrayEquals("The private key password should have been erased.", new char[passwordA02.getValue().length], passwordA02.getValue()); assertEquals("The private key package is not correct.", "com.example.licensing.private", descriptorA01.getValue().getPackageName()); assertEquals("The public key package is not correct.", "com.example.licensing.public", descriptorA02.getValue().getPackageName()); assertEquals("The public password package is not correct.", "com.example.licensing.public", descriptorB01.getValue().getPackageName()); assertEquals("The private password package is not correct.", "com.example.licensing.private", descriptorB02.getValue().getPackageName()); assertEquals("The private key class is not correct.", "PrivateKey02", descriptorA01.getValue().getClassName()); assertEquals("The public key class is not correct.", "PublicKey02", descriptorA02.getValue().getClassName()); assertEquals("The public password class is not correct.", "PublicPassword02", descriptorB01.getValue().getClassName()); assertEquals("The private password class is not correct.", "PrivatePassword02", descriptorB02.getValue().getClassName()); } finally { EasyMock.verify(this.console.cli, privateKey, publicKey); } }
From source file:com.netscape.cms.servlet.csadmin.ConfigurationUtils.java
public static KeyPair loadKeyPair(String nickname, String token) throws Exception { logger.debug("ConfigurationUtils: loadKeyPair(" + nickname + ", " + token + ")"); CryptoManager cm = CryptoManager.getInstance(); if (!CryptoUtil.isInternalToken(token)) { nickname = token + ":" + nickname; }/*from w w w. ja v a 2 s .c o m*/ X509Certificate cert = cm.findCertByNickname(nickname); PublicKey publicKey = cert.getPublicKey(); PrivateKey privateKey = cm.findPrivKeyByCert(cert); return new KeyPair(publicKey, privateKey); }
From source file:org.ejbca.core.ejb.ca.caadmin.CAAdminSessionBean.java
/** * Method that import CA token keys from a P12 file. Was originally used when upgrading from old EJBCA versions. Only supports SHA1 and SHA256 * with RSA or ECDSA and SHA1 with DSA.//from ww w.j av a 2 s . c o m * @throws OperatorCreationException * @throws AuthorizationDeniedException */ private CAToken importKeysToCAToken(AuthenticationToken authenticationToken, String authenticationCode, Properties caTokenProperties, PrivateKey privatekey, PublicKey publickey, PrivateKey privateEncryptionKey, PublicKey publicEncryptionKey, Certificate[] caSignatureCertChain, int caId) throws CryptoTokenAuthenticationFailedException, IllegalCryptoTokenException, OperatorCreationException, AuthorizationDeniedException { // If we don't give an authentication code, perhaps we have autoactivation enabled if (StringUtils.isEmpty(authenticationCode)) { String msg = intres.getLocalizedMessage("token.authcodemissing", Integer.valueOf(caId)); log.info(msg); throw new CryptoTokenAuthenticationFailedException(msg); } if (caTokenProperties == null) { caTokenProperties = new Properties(); } try { // Currently only RSA keys are supported KeyStore keystore = KeyStore.getInstance("PKCS12", "BC"); keystore.load(null, null); // The CAs certificate is first in chain Certificate cacert = caSignatureCertChain[0]; // Assume that the same hash algorithm is used for signing that was used to sign this CA cert String signatureAlgorithm = AlgorithmTools.getSignatureAlgorithm(cacert); String keyAlg = AlgorithmTools.getKeyAlgorithm(publickey); if (keyAlg == null) { throw new IllegalCryptoTokenException( "Unknown public key type: " + publickey.getAlgorithm() + " (" + publickey.getClass() + ")"); } // import sign keys. final Certificate[] certchain = new Certificate[1]; certchain[0] = CertTools.genSelfCert("CN=dummy", 36500, null, privatekey, publickey, signatureAlgorithm, true); keystore.setKeyEntry(CAToken.SOFTPRIVATESIGNKEYALIAS, privatekey, null, certchain); // generate enc keys. // Encryption keys must be RSA still final String encryptionAlgorithm = AlgorithmTools.getEncSigAlgFromSigAlg(signatureAlgorithm); keyAlg = AlgorithmTools.getKeyAlgorithmFromSigAlg(encryptionAlgorithm); final String enckeyspec = "2048"; KeyPair enckeys = null; if (publicEncryptionKey == null || privateEncryptionKey == null) { enckeys = KeyTools.genKeys(enckeyspec, keyAlg); } else { enckeys = new KeyPair(publicEncryptionKey, privateEncryptionKey); } // generate dummy certificate certchain[0] = CertTools.genSelfCert("CN=dummy2", 36500, null, enckeys.getPrivate(), enckeys.getPublic(), encryptionAlgorithm, true); keystore.setKeyEntry(CAToken.SOFTPRIVATEDECKEYALIAS, enckeys.getPrivate(), null, certchain); // Set the token properties caTokenProperties.setProperty(CATokenConstants.CAKEYPURPOSE_CERTSIGN_STRING, CAToken.SOFTPRIVATESIGNKEYALIAS); caTokenProperties.setProperty(CATokenConstants.CAKEYPURPOSE_CRLSIGN_STRING, CAToken.SOFTPRIVATESIGNKEYALIAS); caTokenProperties.setProperty(CATokenConstants.CAKEYPURPOSE_DEFAULT_STRING, CAToken.SOFTPRIVATEDECKEYALIAS); // Write the keystore to byte[] that we can feed to crypto token factory final char[] authCode = authenticationCode.toCharArray(); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); keystore.store(baos, authCode); // Now we have the PKCS12 keystore, from this we can create the CAToken final Properties cryptoTokenProperties = new Properties(); int cryptoTokenId; try { cryptoTokenId = createCryptoTokenWithUniqueName(authenticationToken, "ImportedCryptoToken" + caId, SoftCryptoToken.class.getName(), cryptoTokenProperties, baos.toByteArray(), authCode); } catch (NoSuchSlotException e1) { throw new RuntimeException( "Attempte to define a slot for a soft crypto token. This should not happen."); } final CAToken catoken = new CAToken(cryptoTokenId, caTokenProperties); // If this is a CVC CA we need to find out the sequence String sequence = CAToken.DEFAULT_KEYSEQUENCE; if (cacert instanceof CardVerifiableCertificate) { CardVerifiableCertificate cvccacert = (CardVerifiableCertificate) cacert; log.debug("Getting sequence from holderRef in CV certificate."); try { sequence = cvccacert.getCVCertificate().getCertificateBody().getHolderReference().getSequence(); } catch (NoSuchFieldException e) { log.error("Can not get sequence from holderRef in CV certificate, using default sequence."); } } log.debug("Setting sequence " + sequence); catoken.setKeySequence(sequence); log.debug("Setting default sequence format " + StringTools.KEY_SEQUENCE_FORMAT_NUMERIC); catoken.setKeySequenceFormat(StringTools.KEY_SEQUENCE_FORMAT_NUMERIC); catoken.setSignatureAlgorithm(signatureAlgorithm); catoken.setEncryptionAlgorithm(encryptionAlgorithm); return catoken; } catch (KeyStoreException e) { throw new IllegalCryptoTokenException(e); } catch (NoSuchProviderException e) { throw new IllegalCryptoTokenException(e); } catch (NoSuchAlgorithmException e) { throw new IllegalCryptoTokenException(e); } catch (CertificateException e) { throw new IllegalCryptoTokenException(e); } catch (IOException e) { throw new IllegalCryptoTokenException(e); } catch (IllegalStateException e) { throw new IllegalCryptoTokenException(e); } catch (InvalidAlgorithmParameterException e) { throw new IllegalCryptoTokenException(e); } catch (CryptoTokenOfflineException e) { throw new IllegalCryptoTokenException(e); } }