List of usage examples for java.security.spec PKCS8EncodedKeySpec PKCS8EncodedKeySpec
public PKCS8EncodedKeySpec(byte[] encodedKey)
From source file:im.whistle.crypt.Crypt.java
/** * Encrypts a message./*from w w w .j a va2 s.c om*/ * @param args Arguments: data, publicKey[, privateKey] * @param callback Callback */ public static void encrypt(JSONArray args, AsyncCallback<JSONArray> callback) { try { PRNGProvider.init(); // Ensure OpenSSL fix // Get the arguments String data = args.getString(0); String pub = args.getString(1); String priv = null; if (args.length() == 3) { priv = args.getString(2); } String sig = null; // Convert everything into byte arrays byte[] dataRaw = data.getBytes("utf-8"); byte[] pubRaw = Base64.decode(stripKey(pub), Base64.DEFAULT); // Generate random AES key and IV byte[] aesKey = new byte[AES_BYTES]; new SecureRandom().nextBytes(aesKey); byte[] aesIv = new byte[16]; // Block size new SecureRandom().nextBytes(aesIv); Cipher c = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC"); c.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(aesKey, "AES"), new IvParameterSpec(aesIv)); // Encrypt data with AES byte[] encData = c.doFinal(dataRaw); // Encrypt aes data with RSA X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(pubRaw); KeyFactory kf = KeyFactory.getInstance("RSA", "BC"); c = Cipher.getInstance("RSA/None/OAEPWithSHA-1AndMGF1Padding", "BC"); c.init(Cipher.ENCRYPT_MODE, kf.generatePublic(publicKeySpec)); c.update(aesKey); c.update(aesIv); byte[] encKey = c.doFinal(); // Concatenate and transform byte[] encRaw = new byte[encKey.length + encData.length]; System.arraycopy(encKey, 0, encRaw, 0, encKey.length); System.arraycopy(encData, 0, encRaw, encKey.length, encData.length); encKey = null; encData = null; String enc = new String(Base64.encode(encRaw /* needed for sign */, Base64.NO_WRAP), "utf-8"); // Sign if (priv != null) { // Fail on error (no try-catch) byte[] privRaw = Base64.decode(stripKey(priv), Base64.DEFAULT); PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privRaw); Signature s = Signature.getInstance("SHA1withRSA", "BC"); s.initSign(kf.generatePrivate(privateKeySpec)); s.update(encRaw); sig = new String(Base64.encode(s.sign(), Base64.NO_WRAP), "utf-8"); } JSONArray res = new JSONArray(); res.put(enc); res.put(sig); callback.success(res); } catch (Exception ex) { Log.w("whistle", "Encrypt error: " + ex.getMessage(), ex); callback.error(ex); } }
From source file:com.hhi.bigdata.platform.push.client.RegisterUtil.java
/** * <pre>/* w w w.j a va2 s .c om*/ * create a SSLSocketFactory instance with given parameters * </pre> * @param keystore * @param password * @return * @throws IOException */ private static PrivateKey getPrivateKey(URI keyFile) throws Exception { InputStream privKeyIs = new FileInputStream(new File(keyFile)); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(IOUtils.toByteArray(privKeyIs)); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return keyFactory.generatePrivate(keySpec); }
From source file:org.apache.jmeter.protocol.oauth.sampler.PrivateKeyReader.java
/** * Read the PEM file and return the key//from w w w. j a va 2 s . c o m * * @return * @throws IOException */ private PrivateKey read() throws IOException { String line; KeyFactory factory; try { factory = KeyFactory.getInstance("RSA"); //$NON-NLS-1$ } catch (NoSuchAlgorithmException e) { throw new IOException("JCE error: " + e.getMessage()); //$NON-NLS-1$ } while ((line = server.readLine(fileName)) != null) { if (line.indexOf(P1_BEGIN_MARKER) != -1) { byte[] keyBytes = readKeyMaterial(P1_END_MARKER); RSAPrivateCrtKeySpec keySpec = getRSAKeySpec(keyBytes); try { return factory.generatePrivate(keySpec); } catch (InvalidKeySpecException e) { throw new IOException("Invalid PKCS#1 PEM file: " + e.getMessage()); //$NON-NLS-1$ } } if (line.indexOf(P8_BEGIN_MARKER) != -1) { byte[] keyBytes = readKeyMaterial(P8_END_MARKER); EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes); try { return factory.generatePrivate(keySpec); } catch (InvalidKeySpecException e) { throw new IOException("Invalid PKCS#8 PEM file: " + e.getMessage()); //$NON-NLS-1$ } } } throw new IOException("Invalid PEM file: no begin marker"); //$NON-NLS-1$ }
From source file:com.buzzcoders.security.cryptoutils.asymmetric.AbstractAsymmetricEncryptionModule.java
public PrivateKey loadPrivateKey(String path) { FileInputStream fis = null;//from w w w . j a v a 2s. c o m try { File filePrivateKey = new File(path); fis = new FileInputStream(path); byte[] encodedPrivateKey = new byte[(int) filePrivateKey.length()]; fis.read(encodedPrivateKey); KeyFactory keyFactory = KeyFactory.getInstance(getAlgorithm()); PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey); PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec); return privateKey; } catch (Exception e) { LOG.error("An error occurred while loading the private key from disk.", e); } finally { IOUtils.closeQuietly(fis); } return null; }
From source file:com.zxy.commons.codec.rsa.AbstractRSAUtils.java
/** * //w w w . j av a 2s.co m * * * @param info ? * @return ? * @throws GeneralSecurityException GeneralSecurityException */ public String decode(String info) throws GeneralSecurityException { byte[] priKeyText = this.getPriKeyText(); PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decodeBase64(priKeyText)); KeyFactory keyFactory = null; if (provider == null) { keyFactory = KeyFactory.getInstance(ALGORITHM); } else { keyFactory = KeyFactory.getInstance(ALGORITHM, provider); } // ?? PrivateKey priKey = keyFactory.generatePrivate(priPKCS8); // ?CipherECB?PKCS5Padding Cipher cipher = null; if (provider == null) { cipher = Cipher.getInstance(ALGORITHM); } else { cipher = Cipher.getInstance(ALGORITHM, provider); } // ? cipher.init(Cipher.DECRYPT_MODE, priKey); byte[] newPlainText = cipher.doFinal(Base64.decodeBase64(info.getBytes())); return new String(newPlainText); }
From source file:org.ebayopensource.fido.uaf.crypto.KeyCodec.java
public static PrivateKey getPrivKey(byte[] bytes) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException { KeyFactory kf = KeyFactory.getInstance("ECDSA", "SC"); return kf.generatePrivate(new PKCS8EncodedKeySpec(bytes)); }
From source file:gemlite.core.util.RSAUtils.java
/** * <P>//from w w w . j a v a2 s .c om * ? * </p> * * @param encryptedData * ? * @param privateKey * ?(BASE64?) * @return * @throws Exception */ public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey) throws Exception { byte[] keyBytes = Base64Utils.decode(privateKey); PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); Key privateK = keyFactory.generatePrivate(pkcs8KeySpec); Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, privateK); int inputLen = encryptedData.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int i = 0; // ? while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_DECRYPT_BLOCK) { cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK); } else { cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * MAX_DECRYPT_BLOCK; } byte[] decryptedData = out.toByteArray(); out.close(); return decryptedData; }
From source file:org.excalibur.core.util.SecurityUtils2.java
public static PrivateKey readPrivateKey(@Nonnull File key) throws IOException, GeneralSecurityException { try (PemReader reader = new PemReader(new FileReader(key))) { PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(reader.readPemObject().getContent()); KeyFactory kf = SecurityUtils.getKeyFactory("RSA"); return kf.generatePrivate(keySpec); }/*w w w . jav a2s . com*/ }
From source file:org.eclipse.che.ide.ext.datasource.server.ssl.KeyStoreObject.java
public void addNewKey(String alias, Iterator<FileItem> uploadedFilesIterator) throws Exception { PrivateKey privateKey = null; Certificate[] certs = null;/* www. ja v a2 s . com*/ while (uploadedFilesIterator.hasNext()) { FileItem fileItem = uploadedFilesIterator.next(); if (!fileItem.isFormField()) { if ("keyFile".equals(fileItem.getFieldName())) { KeyFactory kf = KeyFactory.getInstance("RSA"); privateKey = kf.generatePrivate(new PKCS8EncodedKeySpec(fileItem.get())); } if ("certFile".equals(fileItem.getFieldName())) { CertificateFactory cf = CertificateFactory.getInstance("X.509"); certs = cf.generateCertificates(fileItem.getInputStream()).toArray(new Certificate[] {}); } } } if (privateKey == null || certs == null) { throw new WebApplicationException( Response.ok("<pre>Can't find input file.</pre>", MediaType.TEXT_HTML).build()); } keystore.setKeyEntry(alias, privateKey, keyStorePassword.toCharArray(), certs); save(); }
From source file:net.jmhertlein.core.crypto.Keys.java
private static PKCS8EncodedKeySpec getPKCS8KeySpec(String file) { byte[] decoded; try (Scanner scan = new Scanner(new File(file))) { String output = ""; while (scan.hasNextLine()) { output += scan.nextLine();//w ww. java2 s . co m } decoded = Base64.decodeBase64(output); } catch (IOException ioe) { //ioe.printStackTrace(); return null; } return new PKCS8EncodedKeySpec(decoded); }