use of java.security.interfaces.RSAPrivateKey in project camel by apache.
the class SftpOperations method createSession.
protected Session createSession(final RemoteFileConfiguration configuration) throws JSchException {
final JSch jsch = new JSch();
JSch.setLogger(new JSchLogger(endpoint.getConfiguration().getJschLoggingLevel()));
SftpConfiguration sftpConfig = (SftpConfiguration) configuration;
if (isNotEmpty(sftpConfig.getCiphers())) {
LOG.debug("Using ciphers: {}", sftpConfig.getCiphers());
Hashtable<String, String> ciphers = new Hashtable<String, String>();
ciphers.put("cipher.s2c", sftpConfig.getCiphers());
ciphers.put("cipher.c2s", sftpConfig.getCiphers());
JSch.setConfig(ciphers);
}
if (isNotEmpty(sftpConfig.getPrivateKeyFile())) {
LOG.debug("Using private keyfile: {}", sftpConfig.getPrivateKeyFile());
if (isNotEmpty(sftpConfig.getPrivateKeyPassphrase())) {
jsch.addIdentity(sftpConfig.getPrivateKeyFile(), sftpConfig.getPrivateKeyPassphrase());
} else {
jsch.addIdentity(sftpConfig.getPrivateKeyFile());
}
}
if (sftpConfig.getPrivateKey() != null) {
LOG.debug("Using private key information from byte array");
byte[] passphrase = null;
if (isNotEmpty(sftpConfig.getPrivateKeyPassphrase())) {
try {
passphrase = sftpConfig.getPrivateKeyPassphrase().getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new JSchException("Cannot transform passphrase to byte[]", e);
}
}
jsch.addIdentity("ID", sftpConfig.getPrivateKey(), null, passphrase);
}
if (sftpConfig.getPrivateKeyUri() != null) {
LOG.debug("Using private key uri : {}", sftpConfig.getPrivateKeyUri());
byte[] passphrase = null;
if (isNotEmpty(sftpConfig.getPrivateKeyPassphrase())) {
try {
passphrase = sftpConfig.getPrivateKeyPassphrase().getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new JSchException("Cannot transform passphrase to byte[]", e);
}
}
try {
InputStream is = ResourceHelper.resolveMandatoryResourceAsInputStream(endpoint.getCamelContext(), sftpConfig.getPrivateKeyUri());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
IOHelper.copyAndCloseInput(is, bos);
jsch.addIdentity("ID", bos.toByteArray(), null, passphrase);
} catch (IOException e) {
throw new JSchException("Cannot read resource: " + sftpConfig.getPrivateKeyUri(), e);
}
}
if (sftpConfig.getKeyPair() != null) {
LOG.debug("Using private key information from key pair");
KeyPair keyPair = sftpConfig.getKeyPair();
if (keyPair.getPrivate() != null && keyPair.getPublic() != null) {
if (keyPair.getPrivate() instanceof RSAPrivateKey && keyPair.getPublic() instanceof RSAPublicKey) {
jsch.addIdentity(new RSAKeyPairIdentity("ID", keyPair), null);
} else if (keyPair.getPrivate() instanceof DSAPrivateKey && keyPair.getPublic() instanceof DSAPublicKey) {
jsch.addIdentity(new DSAKeyPairIdentity("ID", keyPair), null);
} else {
LOG.warn("Only RSA and DSA key pairs are supported");
}
} else {
LOG.warn("PrivateKey and PublicKey in the KeyPair must be filled");
}
}
if (isNotEmpty(sftpConfig.getKnownHostsFile())) {
LOG.debug("Using knownhosts file: {}", sftpConfig.getKnownHostsFile());
jsch.setKnownHosts(sftpConfig.getKnownHostsFile());
}
if (isNotEmpty(sftpConfig.getKnownHostsUri())) {
LOG.debug("Using known hosts uri: {}", sftpConfig.getKnownHostsUri());
try {
InputStream is = ResourceHelper.resolveMandatoryResourceAsInputStream(endpoint.getCamelContext(), sftpConfig.getKnownHostsUri());
jsch.setKnownHosts(is);
} catch (IOException e) {
throw new JSchException("Cannot read resource: " + sftpConfig.getKnownHostsUri(), e);
}
}
if (sftpConfig.getKnownHosts() != null) {
LOG.debug("Using known hosts information from byte array");
jsch.setKnownHosts(new ByteArrayInputStream(sftpConfig.getKnownHosts()));
}
String knownHostsFile = sftpConfig.getKnownHostsFile();
if (knownHostsFile == null && sftpConfig.isUseUserKnownHostsFile()) {
knownHostsFile = System.getProperty("user.home") + "/.ssh/known_hosts";
LOG.info("Known host file not configured, using user known host file: {}", knownHostsFile);
}
if (ObjectHelper.isNotEmpty(knownHostsFile)) {
LOG.debug("Using known hosts information from file: {}", knownHostsFile);
jsch.setKnownHosts(knownHostsFile);
}
final Session session = jsch.getSession(configuration.getUsername(), configuration.getHost(), configuration.getPort());
if (isNotEmpty(sftpConfig.getStrictHostKeyChecking())) {
LOG.debug("Using StrickHostKeyChecking: {}", sftpConfig.getStrictHostKeyChecking());
session.setConfig("StrictHostKeyChecking", sftpConfig.getStrictHostKeyChecking());
}
session.setServerAliveInterval(sftpConfig.getServerAliveInterval());
session.setServerAliveCountMax(sftpConfig.getServerAliveCountMax());
// compression
if (sftpConfig.getCompression() > 0) {
LOG.debug("Using compression: {}", sftpConfig.getCompression());
session.setConfig("compression.s2c", "zlib@openssh.com,zlib,none");
session.setConfig("compression.c2s", "zlib@openssh.com,zlib,none");
session.setConfig("compression_level", Integer.toString(sftpConfig.getCompression()));
}
// set the PreferredAuthentications
if (sftpConfig.getPreferredAuthentications() != null) {
LOG.debug("Using PreferredAuthentications: {}", sftpConfig.getPreferredAuthentications());
session.setConfig("PreferredAuthentications", sftpConfig.getPreferredAuthentications());
}
// set user information
session.setUserInfo(new ExtendedUserInfo() {
public String getPassphrase() {
return null;
}
public String getPassword() {
return configuration.getPassword();
}
public boolean promptPassword(String s) {
return true;
}
public boolean promptPassphrase(String s) {
return true;
}
public boolean promptYesNo(String s) {
LOG.warn("Server asks for confirmation (yes|no): " + s + ". Camel will answer no.");
// Return 'false' indicating modification of the hosts file is disabled.
return false;
}
public void showMessage(String s) {
LOG.trace("Message received from Server: " + s);
}
public String[] promptKeyboardInteractive(String destination, String name, String instruction, String[] prompt, boolean[] echo) {
// must return an empty array if password is null
if (configuration.getPassword() == null) {
return new String[0];
} else {
return new String[] { configuration.getPassword() };
}
}
});
// set the SO_TIMEOUT for the time after the connect phase
if (configuration.getSoTimeout() > 0) {
session.setTimeout(configuration.getSoTimeout());
}
// set proxy if configured
if (proxy != null) {
session.setProxy(proxy);
}
return session;
}
use of java.security.interfaces.RSAPrivateKey in project android_frameworks_base by ParanoidAndroid.
the class AndroidKeyStoreTest method testKeyStore_GetKey_NoPassword_Encrypted_Success.
public void testKeyStore_GetKey_NoPassword_Encrypted_Success() throws Exception {
setupPassword();
mKeyStore.load(null, null);
assertTrue(mAndroidKeyStore.importKey(Credentials.USER_PRIVATE_KEY + TEST_ALIAS_1, FAKE_KEY_1, KeyStore.UID_SELF, KeyStore.FLAG_ENCRYPTED));
assertTrue(mAndroidKeyStore.put(Credentials.USER_CERTIFICATE + TEST_ALIAS_1, FAKE_USER_1, KeyStore.UID_SELF, KeyStore.FLAG_ENCRYPTED));
assertTrue(mAndroidKeyStore.put(Credentials.CA_CERTIFICATE + TEST_ALIAS_1, FAKE_CA_1, KeyStore.UID_SELF, KeyStore.FLAG_ENCRYPTED));
Key key = mKeyStore.getKey(TEST_ALIAS_1, null);
assertNotNull("Key should exist", key);
assertTrue("Should be a RSAPrivateKey", key instanceof RSAPrivateKey);
RSAPrivateKey actualKey = (RSAPrivateKey) key;
KeyFactory keyFact = KeyFactory.getInstance("RSA");
PrivateKey expectedKey = keyFact.generatePrivate(new PKCS8EncodedKeySpec(FAKE_KEY_1));
assertEquals("Inserted key should be same as retrieved key", ((RSAPrivateKey) expectedKey).getModulus(), actualKey.getModulus());
}
use of java.security.interfaces.RSAPrivateKey in project android_frameworks_base by ParanoidAndroid.
the class AndroidKeyStoreTest method testKeyStore_GetKey_NoPassword_Unencrypted_Success.
public void testKeyStore_GetKey_NoPassword_Unencrypted_Success() throws Exception {
mKeyStore.load(null, null);
assertTrue(mAndroidKeyStore.importKey(Credentials.USER_PRIVATE_KEY + TEST_ALIAS_1, FAKE_KEY_1, KeyStore.UID_SELF, KeyStore.FLAG_NONE));
assertTrue(mAndroidKeyStore.put(Credentials.USER_CERTIFICATE + TEST_ALIAS_1, FAKE_USER_1, KeyStore.UID_SELF, KeyStore.FLAG_NONE));
assertTrue(mAndroidKeyStore.put(Credentials.CA_CERTIFICATE + TEST_ALIAS_1, FAKE_CA_1, KeyStore.UID_SELF, KeyStore.FLAG_NONE));
Key key = mKeyStore.getKey(TEST_ALIAS_1, null);
assertNotNull("Key should exist", key);
assertTrue("Should be a RSAPrivateKey", key instanceof RSAPrivateKey);
RSAPrivateKey actualKey = (RSAPrivateKey) key;
KeyFactory keyFact = KeyFactory.getInstance("RSA");
PrivateKey expectedKey = keyFact.generatePrivate(new PKCS8EncodedKeySpec(FAKE_KEY_1));
assertEquals("Inserted key should be same as retrieved key", ((RSAPrivateKey) expectedKey).getModulus(), actualKey.getModulus());
}
use of java.security.interfaces.RSAPrivateKey in project jersey by jersey.
the class RsaSha1Method method sign.
/**
* Generates the RSA-SHA1 signature of OAuth request elements.
*
* @param baseString the combined OAuth elements to sign.
* @param secrets the secrets object containing the private key for generating the signature.
* @return the OAuth signature, in base64-encoded form.
* @throws InvalidSecretException if the supplied secret is not valid.
*/
@Override
public String sign(final String baseString, final OAuth1Secrets secrets) throws InvalidSecretException {
final Signature signature;
try {
signature = Signature.getInstance(SIGNATURE_ALGORITHM);
} catch (final NoSuchAlgorithmException nsae) {
throw new IllegalStateException(nsae);
}
byte[] decodedPrivateKey;
try {
decodedPrivateKey = Base64.decode(secrets.getConsumerSecret());
} catch (final IOException ioe) {
throw new InvalidSecretException(LocalizationMessages.ERROR_INVALID_CONSUMER_SECRET(ioe));
}
final KeyFactory keyFactory;
try {
keyFactory = KeyFactory.getInstance(KEY_TYPE);
} catch (final NoSuchAlgorithmException nsae) {
throw new IllegalStateException(nsae);
}
final EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedPrivateKey);
final RSAPrivateKey rsaPrivateKey;
try {
rsaPrivateKey = (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
} catch (final InvalidKeySpecException ikse) {
throw new IllegalStateException(ikse);
}
try {
signature.initSign(rsaPrivateKey);
} catch (final InvalidKeyException ike) {
throw new IllegalStateException(ike);
}
try {
signature.update(baseString.getBytes());
} catch (final SignatureException se) {
throw new IllegalStateException(se);
}
final byte[] rsasha1;
try {
rsasha1 = signature.sign();
} catch (final SignatureException se) {
throw new IllegalStateException(se);
}
return Base64.encode(rsasha1);
}
use of java.security.interfaces.RSAPrivateKey in project chromeview by pwnall.
the class AndroidKeyStore method getOpenSSLHandleForPrivateKey.
/**
* Return the system EVP_PKEY handle corresponding to a given PrivateKey
* object, obtained through reflection.
*
* This shall only be used when the "NONEwithRSA" signature is not
* available, as described in rawSignDigestWithPrivateKey(). I.e.
* never use this on Android 4.2 or higher.
*
* This can only work in Android 4.0.4 and higher, for older versions
* of the platform (e.g. 4.0.3), there is no system OpenSSL EVP_PKEY,
* but the private key contents can be retrieved directly with
* the getEncoded() method.
*
* This assumes that the target device uses a vanilla AOSP
* implementation of its java.security classes, which is also
* based on OpenSSL (fortunately, no OEM has apperently changed to
* a different implementation, according to the Android team).
*
* Note that the object returned was created with the platform version
* of OpenSSL, and _not_ the one that comes with Chromium. Whether the
* object can be used safely with the Chromium OpenSSL library depends
* on differences between their actual ABI / implementation details.
*
* To better understand what's going on below, please refer to the
* following source files in the Android 4.0.4 and 4.1 source trees:
* libcore/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLRSAPrivateKey.java
* libcore/luni/src/main/native/org_apache_harmony_xnet_provider_jsse_NativeCrypto.cpp
*
* @param privateKey The PrivateKey handle.
* @return The EVP_PKEY handle, as a 32-bit integer (0 if not available)
*/
@CalledByNative
public static int getOpenSSLHandleForPrivateKey(PrivateKey privateKey) {
// Sanity checks
if (privateKey == null) {
Log.e(TAG, "privateKey == null");
return 0;
}
if (!(privateKey instanceof RSAPrivateKey)) {
Log.e(TAG, "does not implement RSAPrivateKey");
return 0;
}
// First, check that this is a proper instance of OpenSSLRSAPrivateKey
// or one of its sub-classes.
Class<?> superClass;
try {
superClass = Class.forName("org.apache.harmony.xnet.provider.jsse.OpenSSLRSAPrivateKey");
} catch (Exception e) {
// This may happen if the target device has a completely different
// implementation of the java.security APIs, compared to vanilla
// Android. Highly unlikely, but still possible.
Log.e(TAG, "Cannot find system OpenSSLRSAPrivateKey class: " + e);
return 0;
}
if (!superClass.isInstance(privateKey)) {
// This may happen if the PrivateKey was not created by the "AndroidOpenSSL"
// provider, which should be the default. That could happen if an OEM decided
// to implement a different default provider. Also highly unlikely.
Log.e(TAG, "Private key is not an OpenSSLRSAPrivateKey instance, its class name is:" + privateKey.getClass().getCanonicalName());
return 0;
}
try {
// Use reflection to invoke the 'getOpenSSLKey()' method on
// the private key. This returns another Java object that wraps
// a native EVP_PKEY. Note that the method is final, so calling
// the superclass implementation is ok.
Method getKey = superClass.getDeclaredMethod("getOpenSSLKey");
getKey.setAccessible(true);
Object opensslKey = null;
try {
opensslKey = getKey.invoke(privateKey);
} finally {
getKey.setAccessible(false);
}
if (opensslKey == null) {
// Bail when detecting OEM "enhancement".
Log.e(TAG, "getOpenSSLKey() returned null");
return 0;
}
// Use reflection to invoke the 'getPkeyContext' method on the
// result of the getOpenSSLKey(). This is an 32-bit integer
// which is the address of an EVP_PKEY object.
Method getPkeyContext;
try {
getPkeyContext = opensslKey.getClass().getDeclaredMethod("getPkeyContext");
} catch (Exception e) {
// Bail here too, something really not working as expected.
Log.e(TAG, "No getPkeyContext() method on OpenSSLKey member:" + e);
return 0;
}
getPkeyContext.setAccessible(true);
int evp_pkey = 0;
try {
evp_pkey = (Integer) getPkeyContext.invoke(opensslKey);
} finally {
getPkeyContext.setAccessible(false);
}
if (evp_pkey == 0) {
// The PrivateKey is probably rotten for some reason.
Log.e(TAG, "getPkeyContext() returned null");
}
return evp_pkey;
} catch (Exception e) {
Log.e(TAG, "Exception while trying to retrieve system EVP_PKEY handle: " + e);
return 0;
}
}
Aggregations