List of usage examples for java.security.spec PKCS8EncodedKeySpec PKCS8EncodedKeySpec
public PKCS8EncodedKeySpec(byte[] encodedKey)
From source file:com.intuit.s3encrypt.S3Encrypt.java
public static void saveKeyPair(String filename, KeyPair keyPair) throws IOException { PublicKey publicKey = keyPair.getPublic(); PrivateKey privateKey = keyPair.getPrivate(); // Save public key to file. X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKey.getEncoded()); FileOutputStream keyfos = new FileOutputStream(filename + ".pub"); keyfos.write(x509EncodedKeySpec.getEncoded()); keyfos.close();/*from w w w .ja v a2 s . c o m*/ // Save private key to file. PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded()); keyfos = new FileOutputStream(filename); keyfos.write(pkcs8EncodedKeySpec.getEncoded()); keyfos.close(); }
From source file:com.owncloud.android.utils.EncryptionUtils.java
/** * Decrypt string with RSA algorithm, ECB mode, OAEPWithSHA-256AndMGF1 padding * Asymmetric encryption, with private and public key * * @param string string to decrypt * @param privateKeyString private key//from w w w .j a v a 2 s .c o m * @return decrypted string */ @RequiresApi(api = Build.VERSION_CODES.KITKAT) public static String decryptStringAsymmetric(String string, String privateKeyString) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, InvalidKeySpecException { Cipher cipher = Cipher.getInstance(RSA_CIPHER); byte[] privateKeyBytes = decodeStringToBase64Bytes(privateKeyString); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes); KeyFactory kf = KeyFactory.getInstance(RSA); PrivateKey privateKey = kf.generatePrivate(keySpec); cipher.init(Cipher.DECRYPT_MODE, privateKey); byte[] bytes = decodeStringToBase64Bytes(string); byte[] encodedBytes = cipher.doFinal(bytes); return decodeBase64BytesToString(encodedBytes); }
From source file:com.intuit.s3encrypt.S3Encrypt.java
public static KeyPair loadKeyPair(String filename, String algorithm) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException { // Read public key from file. FileInputStream keyfis = new FileInputStream(filename + ".pub"); byte[] encodedPublicKey = new byte[keyfis.available()]; keyfis.read(encodedPublicKey);/*w ww. j a v a2 s . co m*/ keyfis.close(); // Read private key from file. keyfis = new FileInputStream(filename); byte[] encodedPrivateKey = new byte[keyfis.available()]; keyfis.read(encodedPrivateKey); keyfis.close(); // Generate KeyPair from public and private keys. KeyFactory keyFactory = KeyFactory.getInstance(algorithm); X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedPublicKey); PublicKey publicKey = keyFactory.generatePublic(publicKeySpec); PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey); PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec); return new KeyPair(publicKey, privateKey); }
From source file:org.kde.kdeconnect.Device.java
public void addLink(NetworkPackage identityPackage, BaseLink link) { //FilesHelper.LogOpenFileCount(); this.protocolVersion = identityPackage.getInt("protocolVersion"); if (identityPackage.has("deviceName")) { this.name = identityPackage.getString("deviceName", this.name); SharedPreferences.Editor editor = settings.edit(); editor.putString("deviceName", this.name); editor.apply();//w w w .j av a 2s . co m } if (identityPackage.has("deviceType")) { this.deviceType = DeviceType.FromString(identityPackage.getString("deviceType", "desktop")); } if (identityPackage.has("certificate")) { String certificateString = identityPackage.getString("certificate"); try { byte[] certificateBytes = Base64.decode(certificateString, 0); certificate = SslHelper.parseCertificate(certificateBytes); Log.i("KDE/Device", "Got certificate "); } catch (Exception e) { e.printStackTrace(); Log.e("KDE/Device", "Error getting certificate"); } } links.add(link); try { SharedPreferences globalSettings = PreferenceManager.getDefaultSharedPreferences(context); byte[] privateKeyBytes = Base64.decode(globalSettings.getString("privateKey", ""), 0); PrivateKey privateKey = KeyFactory.getInstance("RSA") .generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes)); link.setPrivateKey(privateKey); } catch (Exception e) { e.printStackTrace(); Log.e("KDE/Device", "Exception reading our own private key"); //Should not happen } Log.i("KDE/Device", "addLink " + link.getLinkProvider().getName() + " -> " + getName() + " active links: " + links.size()); if (!pairingHandlers.containsKey(link.getName())) { BasePairingHandler.PairingHandlerCallback callback = new BasePairingHandler.PairingHandlerCallback() { @Override public void incomingRequest() { for (PairingCallback cb : pairingCallback) { cb.incomingRequest(); } } @Override public void pairingDone() { Device.this.pairingDone(); } @Override public void pairingFailed(String error) { for (PairingCallback cb : pairingCallback) { cb.pairingFailed(error); } } @Override public void unpaired() { unpairInternal(); } }; pairingHandlers.put(link.getName(), link.getPairingHandler(this, callback)); } Set<String> outgoingCapabilities = identityPackage.getStringSet("outgoingCapabilities", null); Set<String> incomingCapabilities = identityPackage.getStringSet("incomingCapabilities", null); if (incomingCapabilities != null && outgoingCapabilities != null) { m_supportedPlugins = new Vector<>( PluginFactory.pluginsForCapabilities(context, incomingCapabilities, outgoingCapabilities)); } else { m_supportedPlugins = new Vector<>(PluginFactory.getAvailablePlugins()); } link.addPackageReceiver(this); reloadPluginsFromSettings(); }
From source file:org.apache.cloudstack.network.ssl.CertServiceImpl.java
public PrivateKey parsePrivateKey(final String key) throws IOException { Preconditions.checkArgument(!Strings.isNullOrEmpty(key)); try (final PemReader pemReader = new PemReader(new StringReader(key));) { final PemObject pemObject = pemReader.readPemObject(); final byte[] content = pemObject.getContent(); final PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(content); final KeyFactory factory = KeyFactory.getInstance("RSA", "BC"); return factory.generatePrivate(privKeySpec); } catch (NoSuchAlgorithmException | NoSuchProviderException e) { throw new IOException("No encryption provider available.", e); } catch (final InvalidKeySpecException e) { throw new IOException("Invalid Key format.", e); }//from w w w. j av a 2s .c o m }
From source file:org.jets3t.service.security.EncryptionUtil.java
/** * Generate an RSA SHA1 signature of the given data using the given private * key DER certificate.//from ww w.j av a 2 s . co m * * Based on example code from: * http://www.java2s.com/Tutorial/Java/0490__Security/RSASignatureGeneration.htm * http://forums.sun.com/thread.jspa?threadID=5175986 * * @throws NoSuchAlgorithmException * @throws InvalidKeyException * @throws SignatureException * @throws InvalidKeySpecException * @throws NoSuchProviderException */ public static byte[] signWithRsaSha1(byte[] derPrivateKeyBytes, byte[] dataToSign) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, InvalidKeySpecException, NoSuchProviderException { // Build an RSA private key from private key data PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(derPrivateKeyBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); RSAPrivateKey privateKey = (RSAPrivateKey) keyFactory.generatePrivate(privSpec); // Sign data Signature signature = Signature.getInstance("SHA1withRSA", "BC"); signature.initSign(privateKey, new SecureRandom()); signature.update(dataToSign); byte[] signatureBytes = signature.sign(); return signatureBytes; }
From source file:org.springframework.boot.actuate.autoconfigure.cloudfoundry.reactive.ReactiveTokenValidatorTests.java
private PrivateKey getPrivateKey() throws InvalidKeySpecException, NoSuchAlgorithmException { String signingKey = "-----BEGIN PRIVATE KEY-----\n" + "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDSbn2Xa72IOcxu\n" + "tcd+qQ6ufZ1VDe98EmpwO4VQrTd37U9kZtWU0KqeSkgnyzIWmlbyWOdbB4/v4uJa\n" + "lGjPQjt9hvd3xOOFXzpj33sWXgMGvGAzopMk64T+7GegOFlDXguA5TZyReM7M51O\n" + "ycYwpAEsKXS+lxcG0UsxpJum/WjOLyHsMnJVnoScVBlRYZ2BMyEOuap69/H3lT/X\n" + "pzlYEM6SrAifsaWvL2f1K7HKBt/yDkDOlZy6xmAMsghnslNSV0FvypTZrQOXia8t\n" + "k6fjA+iN+P0LDZAgKxzn4/B/bV8/6HN/7VZJEdudi/y5qdE7SBnx6QZqCEz/YfqC\n" + "olujacgnAgMBAAECggEAc9X2tJ/OWWrXqinOg160gkELloJxTi8lAFsDbAGuAwpT\n" + "JcWl1KF5CmGBjsY/8ElNi2J9GJL1HOwcBhikCVNARD1DhF6RkB13mvquWwWtTMvt\n" + "eP8JWM19DIc+E+hw2rCuTGng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BLPlBaGPwMi2bzB\n" + "gYjmUomvx/fqOTQks9Rc4PIMB43p6Rdj0sh+52SKPDR2eHbwsmpuQUXnAs20BPPI\n" + "J/OOn5zOs8yf26os0q3+JUM=\n-----END PRIVATE KEY-----"; String privateKey = signingKey.replace("-----BEGIN PRIVATE KEY-----\n", ""); privateKey = privateKey.replace("-----END PRIVATE KEY-----", ""); byte[] pkcs8EncodedBytes = Base64.decodeBase64(privateKey); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pkcs8EncodedBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return keyFactory.generatePrivate(keySpec); }
From source file:com.arm.connector.bridge.core.Utils.java
static public PrivateKey createPrivateKeyFromPEM(ErrorLogger logger, String pem, String algorithm) { try {/* w w w .j av a 2s.c o m*/ String temp = Utils.escapeChars(pem); String privKeyPEM = temp.replace("-----BEGIN RSA PRIVATE KEY-----", ""); privKeyPEM = privKeyPEM.replace("-----END RSA PRIVATE KEY-----", ""); // DEBUG //logger.info("createPrivateKeyFromPEM: " + privKeyPEM); Base64 b64 = new Base64(); byte[] decoded = b64.decode(privKeyPEM); PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decoded); KeyFactory kf = KeyFactory.getInstance(algorithm); return kf.generatePrivate(spec); } catch (NoSuchAlgorithmException | InvalidKeySpecException ex) { // exception caught logger.warning("createPrivateKeyFromPEM: Exception during private key gen", ex); } return null; }
From source file:org.alfresco.encryption.AlfrescoKeyStoreImpl.java
void importPrivateKey(String keyAlias, String keyPassword, InputStream fl, InputStream certstream) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, CertificateException, KeyStoreException {/*from w w w . java2s . c o m*/ KeyInfoManager keyInfoManager = null; writeLock.lock(); try { keyInfoManager = getKeyInfoManager(getKeyMetaDataFileLocation()); KeyStore ks = loadKeyStore(getKeyStoreParameters(), keyInfoManager); // loading Key byte[] keyBytes = new byte[fl.available()]; KeyFactory kf = KeyFactory.getInstance("RSA"); fl.read(keyBytes, 0, fl.available()); fl.close(); PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(keyBytes); PrivateKey key = kf.generatePrivate(keysp); // loading CertificateChain CertificateFactory cf = CertificateFactory.getInstance("X.509"); @SuppressWarnings("rawtypes") Collection c = cf.generateCertificates(certstream); Certificate[] certs = new Certificate[c.toArray().length]; certs = (Certificate[]) c.toArray(new Certificate[0]); // storing keystore ks.setKeyEntry(keyAlias, key, keyPassword.toCharArray(), certs); if (logger.isDebugEnabled()) { logger.debug("Key and certificate stored."); logger.debug("Alias:" + keyAlias); } ks.store(new FileOutputStream(getKeyStoreParameters().getLocation()), keyPassword.toCharArray()); } finally { if (keyInfoManager != null) { keyInfoManager.clear(); } writeLock.unlock(); } }
From source file:com.vmware.identity.idm.server.ServerUtils.java
public static PrivateKey getPrivateKeyValue(LdapValue[] value) { PrivateKey privateKey = null; if ((value != null) && (value.length == 1)) { byte[] privateKeyBytes = value[0].getValue(); if (privateKeyBytes != null) { try { KeyFactory keyFactory = KeyFactory.getInstance("RSA"); EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes); privateKey = keyFactory.generatePrivate(privateKeySpec); } catch (NoSuchAlgorithmException ex1) { throw new RuntimeException("No such algorithm"); } catch (InvalidKeySpecException ex2) { throw new RuntimeException("Invalid key spec"); }//from w ww .j a v a 2 s. co m } } return privateKey; }