本文整理汇总了Java中org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter.getKeyPair方法的典型用法代码示例。如果您正苦于以下问题:Java JcaPEMKeyConverter.getKeyPair方法的具体用法?Java JcaPEMKeyConverter.getKeyPair怎么用?Java JcaPEMKeyConverter.getKeyPair使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter
的用法示例。
在下文中一共展示了JcaPEMKeyConverter.getKeyPair方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: createKeyPair
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; //导入方法依赖的package包/类
/**
* Utility method to decode a PEM encoded private key string to a PrivateKey instance
* @param key
* - a PEM encoded private key string
* @return - decoded PrivateKey instance
*/
public static KeyPair createKeyPair(String key) {
AssertUtil.assertNotNull(key, "key");
String decryptedKey = EncryptionUtils.decrypt(key);
try (PEMParser parser = new PEMParser(new StringReader(decryptedKey))) {
JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
PEMKeyPair keyPair = (PEMKeyPair) parser.readObject();
if (keyPair == null) {
throw new RuntimeException("A valid key pair was not found");
}
return converter.getKeyPair(keyPair);
} catch (IOException e) {
throw new RuntimeException("Failed to create key pair", e);
}
}
示例2: getPrivateKeyFromPEM
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; //导入方法依赖的package包/类
private static PrivateKey getPrivateKeyFromPEM(final Reader keyReader)
throws IOException {
final JcaPEMKeyConverter jcaPEMKeyConverter = new JcaPEMKeyConverter();
final PEMParser pem = new PEMParser(keyReader);
PrivateKey key;
Object pemContent = pem.readObject();
if(pemContent instanceof PEMKeyPair) {
PEMKeyPair pemKeyPair = (PEMKeyPair)pemContent;
KeyPair keyPair = jcaPEMKeyConverter.getKeyPair(pemKeyPair);
key = keyPair.getPrivate();
} else if (pemContent instanceof PrivateKeyInfo) {
PrivateKeyInfo privateKeyInfo = (PrivateKeyInfo) pemContent;
key = jcaPEMKeyConverter.getPrivateKey(privateKeyInfo);
} else {
throw new IllegalArgumentException("Unsupported private key format '" + pemContent.getClass().getSimpleName() + '"');
}
pem.close();
return key;
}
示例3: readKeyPairFromFile
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; //导入方法依赖的package包/类
/**
* Reads a keypair from a File.
*
* @throws IOException If an error occurs while reading the file.
* @throws InvalidKeySpecException If the key isn't encoded in x509.
*/
public static KeyPair readKeyPairFromFile(File file) throws IOException, InvalidKeySpecException {
PEMParser parser =
new PEMParser(new InputStreamReader(new FileInputStream(file), Constants.charset));
Object obj = parser.readObject();
parser.close();
if (obj instanceof PEMKeyPair) {
PEMKeyPair pem = (PEMKeyPair) obj;
JcaPEMKeyConverter conv = new JcaPEMKeyConverter();
return conv.getKeyPair(pem);
}
return null;
}
示例4: doOpenSslTestFile
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; //导入方法依赖的package包/类
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");
}
}
示例5: createAndInitKeyManagerFactory
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; //导入方法依赖的package包/类
private KeyManagerFactory createAndInitKeyManagerFactory() throws Exception {
X509Certificate certHolder = certificateConverter.getCertificate((X509CertificateHolder) readPEMFile(cert));
Object keyObject = readPEMFile(privateKey);
char[] passwordCharArray = "".toCharArray();
if (!StringUtils.isEmpty(password)) {
passwordCharArray = password.toCharArray();
}
JcaPEMKeyConverter keyConverter = new JcaPEMKeyConverter().setProvider("BC");
KeyPair key;
if (keyObject instanceof PEMEncryptedKeyPair) {
PEMDecryptorProvider provider = new JcePEMDecryptorProviderBuilder().build(passwordCharArray);
key = keyConverter.getKeyPair(((PEMEncryptedKeyPair) keyObject).decryptKeyPair(provider));
} else {
key = keyConverter.getKeyPair((PEMKeyPair) keyObject);
}
KeyStore clientKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
clientKeyStore.load(null, null);
clientKeyStore.setCertificateEntry("cert", certHolder);
clientKeyStore.setKeyEntry("private-key", key.getPrivate(), passwordCharArray, new Certificate[] { certHolder });
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(clientKeyStore, passwordCharArray);
return keyManagerFactory;
}
示例6: createAndInitKeyManagerFactory
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; //导入方法依赖的package包/类
private KeyManagerFactory createAndInitKeyManagerFactory() throws Exception {
X509Certificate certHolder;
Object keyObject;
if (certFileName != null && privateKeyFileName != null) {
certHolder = readCertFile(cert);
keyObject = readPrivateKeyFile(privateKey);
} else {
certHolder = certificateConverter.getCertificate((X509CertificateHolder) readPEMFile(cert));
keyObject = readPEMFile(privateKey);
}
char[] passwordCharArray = "".toCharArray();
if (!StringUtils.isEmpty(password)) {
passwordCharArray = password.toCharArray();
}
JcaPEMKeyConverter keyConverter = new JcaPEMKeyConverter().setProvider("BC");
KeyPair key;
if (keyObject instanceof PEMEncryptedKeyPair) {
PEMDecryptorProvider provider = new JcePEMDecryptorProviderBuilder().build(passwordCharArray);
key = keyConverter.getKeyPair(((PEMEncryptedKeyPair) keyObject).decryptKeyPair(provider));
} else {
key = keyConverter.getKeyPair((PEMKeyPair) keyObject);
}
KeyStore clientKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
clientKeyStore.load(null, null);
clientKeyStore.setCertificateEntry("cert", certHolder);
clientKeyStore.setKeyEntry("private-key",
key.getPrivate(),
passwordCharArray,
new Certificate[]{certHolder});
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(clientKeyStore, passwordCharArray);
return keyManagerFactory;
}
示例7: getEncryptionCredential
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; //导入方法依赖的package包/类
private Credential getEncryptionCredential(final WsFederationConfiguration config) {
try {
// This will need to contain the private keypair in PEM format
final BufferedReader br = new BufferedReader(new InputStreamReader(config.getEncryptionPrivateKey().getInputStream()));
Security.addProvider(new BouncyCastleProvider());
final PEMParser pemParser = new PEMParser(br);
final Object privateKeyPemObject = pemParser.readObject();
final JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider(new BouncyCastleProvider());
final KeyPair kp;
if (privateKeyPemObject instanceof PEMEncryptedKeyPair) {
final PEMEncryptedKeyPair ckp = (PEMEncryptedKeyPair) privateKeyPemObject;
final PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder()
.build(config.getEncryptionPrivateKeyPassword().toCharArray());
kp = converter.getKeyPair(ckp.decryptKeyPair(decProv));
} else {
kp = converter.getKeyPair((PEMKeyPair) privateKeyPemObject);
}
final X509CertParser certParser = new X509CertParser();
// This is the certificate shared with ADFS in DER format, i.e certificate.crt
certParser.engineInit(config.getEncryptionCertificate().getInputStream());
final X509CertificateObject cert = (X509CertificateObject) certParser.engineRead();
return new BasicX509Credential(cert, kp.getPrivate());
} catch (final Exception e) {
throw Throwables.propagate(e);
}
}
示例8: readKeyPair
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; //导入方法依赖的package包/类
/**
* Reads a base64-format PEM key and returns a Java KeyPair for it.
* @param privateKey PEM-encoded private key
*/
public static KeyPair readKeyPair(String privateKey) {
try (StringReader keyReader = new StringReader(privateKey);
PEMParser pemReader = new PEMParser(keyReader)) {
JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
return converter.getKeyPair((PEMKeyPair) pemReader.readObject());
} catch (IOException x) {
// Shouldn't occur, since we're only reading from strings
throw new RuntimeException(x);
}
}
示例9: convert
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; //导入方法依赖的package包/类
@Override
public KeyPair convert(String source) {
PEMParser pemParser = new PEMParser(new StringReader(source));
try {
PEMKeyPair keyPair = (PEMKeyPair) pemParser.readObject();
JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
return converter.getKeyPair(keyPair);
} catch (Exception ignored) {
return null;
}
}
示例10: startSession
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; //导入方法依赖的package包/类
@Deprecated
private void startSession() throws IOException {
final ConnectFuture connectFuture;
connectFuture = client.connect(deviceInfo.name(),
deviceInfo.ip().toString(),
deviceInfo.port())
.verify(connectTimeout, TimeUnit.SECONDS);
session = connectFuture.getSession();
//Using the device ssh key if possible
if (deviceInfo.getKey() != null) {
try (PEMParser pemParser = new PEMParser(new CharArrayReader(deviceInfo.getKey()))) {
JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME);
try {
KeyPair kp = converter.getKeyPair((PEMKeyPair) pemParser.readObject());
session.addPublicKeyIdentity(kp);
} catch (IOException e) {
throw new NetconfException("Failed to authenticate session with device " +
deviceInfo + "check key to be a valid key", e);
}
}
} else {
session.addPasswordIdentity(deviceInfo.password());
}
session.auth().verify(connectTimeout, TimeUnit.SECONDS);
Set<ClientSession.ClientSessionEvent> event = session.waitFor(
ImmutableSet.of(ClientSession.ClientSessionEvent.WAIT_AUTH,
ClientSession.ClientSessionEvent.CLOSED,
ClientSession.ClientSessionEvent.AUTHED), 0);
if (!event.contains(ClientSession.ClientSessionEvent.AUTHED)) {
log.debug("Session closed {} {}", event, session.isClosed());
throw new NetconfException("Failed to authenticate session with device " +
deviceInfo + "check the user/pwd or key");
}
openChannel();
}
示例11: getEncryptionCredential
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; //导入方法依赖的package包/类
private static Credential getEncryptionCredential(final WsFederationConfiguration config) {
try {
// This will need to contain the private keypair in PEM format
LOGGER.debug("Locating encryption credential private key [{}]", config.getEncryptionPrivateKey());
final BufferedReader br = new BufferedReader(new InputStreamReader(
config.getEncryptionPrivateKey().getInputStream(), StandardCharsets.UTF_8));
Security.addProvider(new BouncyCastleProvider());
LOGGER.debug("Parsing credential private key");
final PEMParser pemParser = new PEMParser(br);
final Object privateKeyPemObject = pemParser.readObject();
final JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider(new BouncyCastleProvider());
final KeyPair kp;
if (privateKeyPemObject instanceof PEMEncryptedKeyPair) {
LOGGER.debug("Encryption private key is an encrypted keypair");
final PEMEncryptedKeyPair ckp = (PEMEncryptedKeyPair) privateKeyPemObject;
final PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder()
.build(config.getEncryptionPrivateKeyPassword().toCharArray());
LOGGER.debug("Attempting to decrypt the encrypted keypair based on the provided encryption private key password");
kp = converter.getKeyPair(ckp.decryptKeyPair(decProv));
} else {
LOGGER.debug("Extracting a keypair from the private key");
kp = converter.getKeyPair((PEMKeyPair) privateKeyPemObject);
}
final X509CertParser certParser = new X509CertParser();
// This is the certificate shared with ADFS in DER format, i.e certificate.crt
LOGGER.debug("Locating encryption certificate [{}]", config.getEncryptionCertificate());
certParser.engineInit(config.getEncryptionCertificate().getInputStream());
LOGGER.debug("Invoking certificate engine to parse the certificate [{}]", config.getEncryptionCertificate());
final X509CertificateObject cert = (X509CertificateObject) certParser.engineRead();
LOGGER.debug("Creating final credential based on the certificate [{}] and the private key", cert.getIssuerDN());
return new BasicX509Credential(cert, kp.getPrivate());
} catch (final Exception e) {
throw Throwables.propagate(e);
}
}
示例12: parsePrivateKey
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; //导入方法依赖的package包/类
/**
* Parses a PrivateKey instance from a PEM representation.
*
* When the provided key is encrypted, the provided pass phrase is applied.
*
* @param pemRepresentation a PEM representation of a private key (cannot be null or empty)
* @param passPhrase optional pass phrase (must be present if the private key is encrypted).
* @return a PrivateKey instance (never null)
*/
public static PrivateKey parsePrivateKey(InputStream pemRepresentation, String passPhrase) throws IOException {
if ( passPhrase == null ) {
passPhrase = "";
}
try (Reader reader = new InputStreamReader(pemRepresentation); //
PEMParser pemParser = new PEMParser(reader)) {
final Object object = pemParser.readObject();
final JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider( "BC" );
final KeyPair kp;
if ( object instanceof PEMEncryptedKeyPair )
{
// Encrypted key - we will use provided password
final PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build( passPhrase.toCharArray() );
kp = converter.getKeyPair( ( (PEMEncryptedKeyPair) object ).decryptKeyPair( decProv ) );
}
else if ( object instanceof PKCS8EncryptedPrivateKeyInfo )
{
// Encrypted key - we will use provided password
try
{
final PKCS8EncryptedPrivateKeyInfo encryptedInfo = (PKCS8EncryptedPrivateKeyInfo) object;
final InputDecryptorProvider provider = new JceOpenSSLPKCS8DecryptorProviderBuilder().build( passPhrase.toCharArray() );
final PrivateKeyInfo privateKeyInfo = encryptedInfo.decryptPrivateKeyInfo( provider );
return converter.getPrivateKey( privateKeyInfo );
}
catch ( PKCSException | OperatorCreationException e )
{
throw new IOException( "Unable to decrypt private key.", e );
}
}
else if ( object instanceof PrivateKeyInfo )
{
return converter.getPrivateKey( (PrivateKeyInfo) object );
}
else
{
// Unencrypted key - no password needed
kp = converter.getKeyPair( (PEMKeyPair) object );
}
return kp.getPrivate();
}
}
示例13: getSocketFactory
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; //导入方法依赖的package包/类
public static SSLSocketFactory getSocketFactory(String caCrtFile,
String crtFile, String keyFile, String password) throws Exception {
char[] passwordCharArray = password == null ? new char[0] : password
.toCharArray();
Security.addProvider(new BouncyCastleProvider());
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate caCert = (X509Certificate) cf
.generateCertificate(new ByteArrayInputStream(Files
.readAllBytes(Paths.get(caCrtFile))));
X509Certificate cert = (X509Certificate) cf
.generateCertificate(new ByteArrayInputStream(Files
.readAllBytes(Paths.get(crtFile))));
File privateKeyFile = new File(keyFile);
PEMParser pemParser = new PEMParser(new FileReader(privateKeyFile));
PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder()
.build(passwordCharArray);
JcaPEMKeyConverter converter = new JcaPEMKeyConverter()
.setProvider("BC");
Object object = pemParser.readObject();
KeyPair kp;
if (object instanceof PEMEncryptedKeyPair) {
kp = converter.getKeyPair(((PEMEncryptedKeyPair) object)
.decryptKeyPair(decProv));
} else {
kp = converter.getKeyPair((PEMKeyPair) object);
}
pemParser.close();
KeyStore caKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
caKeyStore.load(null, null);
caKeyStore.setCertificateEntry("ca-certificate", caCert);
TrustManagerFactory trustManagerFactory = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(caKeyStore);
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null, null);
keyStore.setCertificateEntry("certificate", cert);
keyStore.setKeyEntry("private-key", kp.getPrivate(), passwordCharArray,
new java.security.cert.Certificate[] { cert });
KeyManagerFactory keyManagerFactory = KeyManagerFactory
.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, passwordCharArray);
SSLContext context = SSLContext.getInstance("TLSv1");
context.init(keyManagerFactory.getKeyManagers(),
trustManagerFactory.getTrustManagers(), null);
return context.getSocketFactory();
}
示例14: registerUser
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; //导入方法依赖的package包/类
/**
* Register a new user
*
* @param user User to register.
* @return Private key in base 64 format
*/
public String registerUser(User user) throws RegistrationException {
try {
HttpClient client = new DefaultHttpClient();
HttpGet rootRequest = new HttpGet(getRootUrl());
HttpResponse response = client.execute(rootRequest);
String responseJson = EntityUtils.toString(response.getEntity());
ObjectMapper mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
HalRoot root = mapper.readValue(responseJson, HalRoot.class);
String usersUrl = root.getUsersLink();
String requestJson = mapper.writeValueAsString(user);
HttpPost userPost = new HttpPost(usersUrl);
userPost.addHeader("Content-Type", "application/json");
userPost.setEntity(new StringEntity(requestJson));
response = client.execute(userPost);
responseJson = EntityUtils.toString(response.getEntity());
if (response.getStatusLine().getStatusCode() == 422) {
HalErrors errors = mapper.readValue(responseJson, HalErrors.class);
throw new RegistrationException(errors.getErrors());
}
User loadedUser = mapper.readValue(responseJson, User.class);
ByteArrayInputStream tube = new ByteArrayInputStream(loadedUser.getPrivateKey().getBytes());
Reader stringReader = new BufferedReader(new InputStreamReader(tube));
PEMParser pemParser = new PEMParser(stringReader);
Object object = pemParser.readObject();
PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().
build(User.hashPasswordForPrivateKey(user).toCharArray());
JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
KeyPair keyPair = converter.getKeyPair(((PEMEncryptedKeyPair) object).decryptKeyPair(decProv));
String base64PrivateKey = Base64.encodeToString(keyPair.getPrivate().getEncoded(), Base64.NO_WRAP);
return base64PrivateKey;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}