List of usage examples for java.security KeyFactory generatePublic
public final PublicKey generatePublic(KeySpec keySpec) throws InvalidKeySpecException
From source file:info.magnolia.cms.security.SecurityUtil.java
public static String decrypt(String message, String encodedKey) throws SecurityException { try {//from ww w .j a v a2 s . co m if (StringUtils.isBlank(encodedKey)) { throw new SecurityException( "Activation key was not found. Please make sure your instance is correctly configured."); } // decode key byte[] binaryKey = hexToByteArray(encodedKey); // create RSA public key cipher Cipher pkCipher = Cipher.getInstance(ALGORITHM, "BC"); try { // create private key X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(binaryKey); KeyFactory kf = KeyFactory.getInstance(ALGORITHM, "BC"); PublicKey pk = kf.generatePublic(publicKeySpec); pkCipher.init(Cipher.DECRYPT_MODE, pk); } catch (InvalidKeySpecException e) { // decrypting with private key? PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(binaryKey); KeyFactory kf = KeyFactory.getInstance(ALGORITHM, "BC"); PrivateKey pk = kf.generatePrivate(privateKeySpec); pkCipher.init(Cipher.DECRYPT_MODE, pk); } // decrypt String[] chunks = StringUtils.split(message, ";"); if (chunks == null) { throw new SecurityException( "The encrypted information is corrupted or incomplete. Please make sure someone is not trying to intercept or modify encrypted message."); } StringBuilder clearText = new StringBuilder(); for (String chunk : chunks) { byte[] byteChunk = hexToByteArray(chunk); clearText.append(new String(pkCipher.doFinal(byteChunk), "UTF-8")); } return clearText.toString(); } catch (NumberFormatException e) { throw new SecurityException( "The encrypted information is corrupted or incomplete. Please make sure someone is not trying to intercept or modify encrypted message.", e); } catch (IOException e) { throw new SecurityException( "Failed to read authentication string. Please use Java version with cryptography support.", e); } catch (NoSuchAlgorithmException e) { throw new SecurityException( "Failed to read authentication string. Please use Java version with cryptography support.", e); } catch (NoSuchPaddingException e) { throw new SecurityException( "Failed to read authentication string. Please use Java version with cryptography support.", e); } catch (InvalidKeySpecException e) { throw new SecurityException( "Failed to read authentication string. Please use Java version with cryptography support.", e); } catch (InvalidKeyException e) { throw new SecurityException( "Failed to read authentication string. Please use Java version with cryptography support.", e); } catch (NoSuchProviderException e) { throw new SecurityException( "Failed to find encryption provider. Please use Java version with cryptography support.", e); } catch (IllegalBlockSizeException e) { throw new SecurityException("Failed to decrypt message. It might have been corrupted during transport.", e); } catch (BadPaddingException e) { throw new SecurityException("Failed to decrypt message. It might have been corrupted during transport.", e); } }
From source file:org.artifactory.security.crypto.CryptoHelper.java
static KeyPair createKeyPair(byte[] encodedPrivateKey, byte[] encodedPublicKey) { try {//w w w . ja v a2s. com EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey); KeyFactory generator = KeyFactory.getInstance(ASYM_ALGORITHM); PrivateKey privateKey = generator.generatePrivate(privateKeySpec); EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedPublicKey); PublicKey publicKey = generator.generatePublic(publicKeySpec); return new KeyPair(publicKey, privateKey); } catch (Exception e) { throw new IllegalArgumentException("Failed to create KeyPair from provided encoded keys", e); } }
From source file:com.forsrc.utils.MyRsa2Utils.java
/** * Gets public key.//w ww .j a va 2s . c o m * * @param key the key * @return the public key * @throws RsaException the rsa exception */ public static PublicKey getPublicKey(String key) throws RsaException { byte[] keyBytes; try { keyBytes = (new Base64()).decode(key); } catch (Exception e) { throw new RsaException(e); } X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = null; try { keyFactory = KeyFactory.getInstance(RsaKey.ALGORITHM); } catch (NoSuchAlgorithmException e) { throw new RsaException(e); } PublicKey publicKey = null; try { publicKey = keyFactory.generatePublic(keySpec); } catch (InvalidKeySpecException e) { throw new RsaException(e); } return publicKey; }
From source file:jenkins.bouncycastle.api.PEMEncodable.java
/** * Creates a {@link PEMEncodable} by decoding PEM formated data from a {@link String} * /* w ww.j a v a2 s . com*/ * @param pem {@link String} with the PEM data * @param passphrase passphrase for the encrypted PEM data. null if PEM data is not passphrase protected. The caller * is responsible for zeroing out the char[] after use to ensure the password does not stay in memory, e.g. with * <code>Arrays.fill(passphrase, (char)0)</code> * @return {@link PEMEncodable} object * @throws IOException launched if a problem exists reading the PEM information * @throws UnrecoverableKeyException in case PEM is passphrase protected and none or wrong is provided */ @Nonnull public static PEMEncodable decode(@Nonnull String pem, @Nullable final char[] passphrase) throws IOException, UnrecoverableKeyException { try (PEMParser parser = new PEMParser(new StringReader(pem));) { Object object = parser.readObject(); JcaPEMKeyConverter kConv = new JcaPEMKeyConverter().setProvider("BC"); // handle supported PEM formats. if (object instanceof PEMEncryptedKeyPair) { if (passphrase != null) { PEMDecryptorProvider dp = new JcePEMDecryptorProviderBuilder().build(passphrase); PEMEncryptedKeyPair ekp = (PEMEncryptedKeyPair) object; return new PEMEncodable(kConv.getKeyPair(ekp.decryptKeyPair(dp))); } else { throw new UnrecoverableKeyException(); } } else if (object instanceof PKCS8EncryptedPrivateKeyInfo) { if (passphrase != null) { InputDecryptorProvider dp = new JceOpenSSLPKCS8DecryptorProviderBuilder().build(passphrase); PKCS8EncryptedPrivateKeyInfo epk = (PKCS8EncryptedPrivateKeyInfo) object; return new PEMEncodable(kConv.getPrivateKey(epk.decryptPrivateKeyInfo(dp))); } else { throw new UnrecoverableKeyException(); } } else if (object instanceof PEMKeyPair) { return new PEMEncodable(kConv.getKeyPair((PEMKeyPair) object)); } else if (object instanceof PrivateKeyInfo) { PrivateKey pk = kConv.getPrivateKey((PrivateKeyInfo) object); // JENKINS-35661 in this case we know how to get the public key too if (pk instanceof RSAPrivateCrtKey) { // obtain public key spec from the private key RSAPrivateCrtKey rsaPK = (RSAPrivateCrtKey) pk; RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(rsaPK.getModulus(), rsaPK.getPublicExponent()); KeyFactory kf = KeyFactory.getInstance("RSA"); return new PEMEncodable(new KeyPair(kf.generatePublic(pubKeySpec), rsaPK)); } return new PEMEncodable(pk); } else if (object instanceof SubjectPublicKeyInfo) { return new PEMEncodable(kConv.getPublicKey((SubjectPublicKeyInfo) object)); } else if (object instanceof X509CertificateHolder) { JcaX509CertificateConverter cConv = new JcaX509CertificateConverter().setProvider("BC"); return new PEMEncodable(cConv.getCertificate((X509CertificateHolder) object)); } else { throw new IOException( "Could not parse PEM, only key pairs, private keys, public keys and certificates are supported. Received " + object.getClass().getName()); } } catch (OperatorCreationException e) { throw new IOException(e.getMessage(), e); } catch (PKCSException | InvalidKeySpecException e) { LOGGER.log(Level.WARNING, "Could not read PEM encrypted information", e); throw new UnrecoverableKeyException(); } catch (CertificateException e) { throw new IOException("Could not read certificate", e); } catch (NoSuchAlgorithmException e) { throw new AssertionError( "RSA algorithm support is mandated by Java Language Specification. See https://docs.oracle.com/javase/7/docs/api/java/security/KeyFactory.html"); } }
From source file:com.bitdubai.fermat_api.layer.all_definition.crypto.asymmetric.util.PublicKeyReaderUtil.java
/** * <p>Decode a RSA public key encoded according to the SSH standard from * the data <code>_buffer</code>. The values of the RSA public key * specification are read in the order/*from ww w . ja v a2 s . com*/ * <ul> * <li>public exponent</li> * <li>modulus</li> * </ul> * With the specification the related RSA public key is generated.</p> * * @param _buffer key / certificate data (certificate or public key * format identifier is already read) * @return RSA public key instance * @throws PublicKeyParseException if the SSH2 public key blob could not be * decoded * @see RSAPublicKeySpec * @see <a href="http://en.wikipedia.org/wiki/RSA">RSA on Wikipedia</a> * @see <a href="http://tools.ietf.org/html/rfc4253#section-6.6">RFC 4253 Section 6.6</a> */ private static PublicKey decodePublicKey(final SSH2DataBuffer _buffer) throws PublicKeyParseException { final BigInteger e = _buffer.readMPint(); final BigInteger n = _buffer.readMPint(); try { final KeyFactory rsaKeyFact = KeyFactory.getInstance("RSA"); final RSAPublicKeySpec rsaPubSpec = new RSAPublicKeySpec(n, e); return rsaKeyFact.generatePublic(rsaPubSpec); } catch (final Exception ex) { throw new PublicKeyParseException( PublicKeyParseException.ErrorCode.SSH2RSA_ERROR_DECODING_PUBLIC_KEY_BLOB, ex); } }
From source file:com.bitdubai.fermat_api.layer.all_definition.crypto.asymmetric.util.PublicKeyReaderUtil.java
/** * <p>Decodes a DSA public key according to the SSH standard from the * data <code>_buffer</code> based on <b>NIST's FIPS-186</b>. The values of * the DSA public key specification are read in the order * <ul>// w ww. j ava 2s. co m * <li>prime p</li> * <li>sub-prime q</li> * <li>base g</li> * <li>public key y</li> * </ul> * With the specification the related DSA public key is generated.</p> * * @param _buffer SSH2 data buffer where the type of the key is already * read * @return DSA public key instance * @throws PublicKeyParseException if the SSH2 public key blob could not be * decoded * @see DSAPublicKeySpec * @see <a href="http://en.wikipedia.org/wiki/Digital_Signature_Algorithm">Digital Signature Algorithm on Wikipedia</a> * @see <a href="http://tools.ietf.org/html/rfc4253#section-6.6">RFC 4253 Section 6.6</a> */ private static PublicKey decodeDSAPublicKey(final SSH2DataBuffer _buffer) throws PublicKeyParseException { final BigInteger p = _buffer.readMPint(); final BigInteger q = _buffer.readMPint(); final BigInteger g = _buffer.readMPint(); final BigInteger y = _buffer.readMPint(); try { final KeyFactory dsaKeyFact = KeyFactory.getInstance("DSA"); final DSAPublicKeySpec dsaPubSpec = new DSAPublicKeySpec(y, p, q, g); return dsaKeyFact.generatePublic(dsaPubSpec); } catch (final Exception e) { throw new PublicKeyParseException( PublicKeyParseException.ErrorCode.SSH2DSA_ERROR_DECODING_PUBLIC_KEY_BLOB, e); } }
From source file:com.arm.connector.bridge.core.Utils.java
static public PublicKey createPublicKeyFromPEM(ErrorLogger logger, String pem, String algorithm) { try {/* w w w . ja v a 2s . c o m*/ String temp = Utils.escapeChars(pem); String publicKeyPEM = temp.replace("-----BEGIN PUBLIC KEY-----", ""); publicKeyPEM = publicKeyPEM.replace("-----END PUBLIC KEY-----", ""); // DEBUG //logger.info("createPublicKeyFromPEM: " + publicKeyPEM); Base64 b64 = new Base64(); byte[] decoded = b64.decode(publicKeyPEM); X509EncodedKeySpec spec = new X509EncodedKeySpec(decoded); KeyFactory kf = KeyFactory.getInstance(algorithm); return kf.generatePublic(spec); } catch (NoSuchAlgorithmException | InvalidKeySpecException ex) { // exception caught logger.warning("createPublicKeyFromPEM: Exception during public key gen", ex); } return null; }
From source file:edu.vt.middleware.crypt.util.CryptReader.java
/** * Reads a DER-encoded X.509 public key from an input stream into a {@link * PublicKey} object.// w w w. j ava2s. com * * @param keyStream Input stream containing DER-encoded X.509 public key. * @param algorithm Name of encryption algorithm used by key. * * @return Public key containing data read from stream. * * @throws CryptException On key format errors. * @throws IOException On key read errors. */ public static PublicKey readPublicKey(final InputStream keyStream, final String algorithm) throws CryptException, IOException { final KeyFactory kf = CryptProvider.getKeyFactory(algorithm); try { final X509EncodedKeySpec keySpec = new X509EncodedKeySpec(readData(keyStream)); return kf.generatePublic(keySpec); } catch (InvalidKeySpecException e) { throw new CryptException("Invalid public key format.", e); } }
From source file:com.sixsq.slipstream.cookie.CryptoUtils.java
static private void setKeyPairFromDb() throws NoSuchAlgorithmException, InvalidKeySpecException, CertificateException { CookieKeyPair ckp = CookieKeyPair.load(); if (ckp == null) { return;/*from w w w .j a v a 2s .c o m*/ } String privateKeyBase64 = ckp.getPrivateKey(); String publicKeyBase64 = ckp.getPublicKey(); if (privateKeyBase64 == null || publicKeyBase64 == null) { return; } byte[] privateKeyBytes = new Base64().decode(privateKeyBase64); KeyFactory keyFactory = KeyFactory.getInstance(keyPairAlgorithm); KeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes); privateKey = keyFactory.generatePrivate(privateKeySpec); byte[] publicKeyBytes = new Base64().decode(publicKeyBase64); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(publicKeyBytes); keyFactory = KeyFactory.getInstance(keyPairAlgorithm); publicKey = keyFactory.generatePublic(x509KeySpec); }
From source file:com.github.woki.payments.adyen.action.CSEUtil.java
public static Cipher rsaCipher(final String cseKeyText) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException, IllegalArgumentException { String[] cseKeyParts = cseKeyText.split("\\|"); if (cseKeyParts.length != 2) { throw new InvalidKeyException("Invalid CSE Key: " + cseKeyText); }//from w w w.ja v a 2s .com KeyFactory keyFactory = KeyFactory.getInstance("RSA"); BigInteger keyComponent1, keyComponent2; try { keyComponent1 = new BigInteger(cseKeyParts[1].toLowerCase(Locale.getDefault()), 16); keyComponent2 = new BigInteger(cseKeyParts[0].toLowerCase(Locale.getDefault()), 16); } catch (NumberFormatException e) { throw new InvalidKeyException("Invalid CSE Key: " + cseKeyText); } RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(keyComponent1, keyComponent2); PublicKey pubKey = keyFactory.generatePublic(pubKeySpec); Cipher result = Cipher.getInstance("RSA/None/PKCS1Padding"); result.init(Cipher.ENCRYPT_MODE, pubKey); return result; }