List of usage examples for java.security.spec PKCS8EncodedKeySpec PKCS8EncodedKeySpec
public PKCS8EncodedKeySpec(byte[] encodedKey)
From source file:info.magnolia.cms.security.SecurityUtil.java
public static String encrypt(String message, String encodedKey) { try {//from ww w. j a v a 2 s. co m // read private key if (StringUtils.isBlank(encodedKey)) { throw new SecurityException( "Activation key was not found. Please make sure your instance is correctly configured."); } byte[] binaryKey = hexToByteArray(encodedKey); // create RSA public key cipher Cipher pkCipher = Cipher.getInstance(ALGORITHM, "BC"); try { // create private key PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(binaryKey); KeyFactory kf = KeyFactory.getInstance(ALGORITHM, "BC"); PrivateKey pk = kf.generatePrivate(privateKeySpec); pkCipher.init(Cipher.ENCRYPT_MODE, pk); } catch (InvalidKeySpecException e) { // encrypting with public key? X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(binaryKey); KeyFactory kf = KeyFactory.getInstance(ALGORITHM, "BC"); PublicKey pk = kf.generatePublic(publicKeySpec); pkCipher.init(Cipher.ENCRYPT_MODE, pk); } // encrypt byte[] bytes = message.getBytes("UTF-8"); // split bit message in chunks int start = 0; StringBuilder chaos = new StringBuilder(); while (start < bytes.length) { byte[] tmp = new byte[Math.min(bytes.length - start, binaryKey.length / 8)]; System.arraycopy(bytes, start, tmp, 0, tmp.length); start += tmp.length; byte[] encrypted = pkCipher.doFinal(tmp); chaos.append(byteArrayToHex(encrypted)); chaos.append(";"); } chaos.setLength(chaos.length() - 1); return chaos.toString(); } catch (IOException e) { throw new SecurityException( "Failed to create authentication string. Please use Java version with cryptography support.", e); } catch (NoSuchAlgorithmException e) { throw new SecurityException( "Failed to create authentication string. Please use Java version with cryptography support.", e); } catch (NoSuchPaddingException e) { throw new SecurityException( "Failed to create authentication string. Please use Java version with cryptography support.", e); } catch (InvalidKeySpecException e) { throw new SecurityException( "Failed to create authentication string. Please use Java version with cryptography support.", e); } catch (InvalidKeyException e) { throw new SecurityException( "Failed to create 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 encrypt string. Please use Java version with cryptography support.", e); } catch (BadPaddingException e) { throw new SecurityException( "Failed to encrypt string. Please use Java version with cryptography support.", e); } }
From source file:net.sf.keystore_explorer.crypto.privatekey.Pkcs8Util.java
/** * Load an unencrypted PKCS #8 private key from the stream. The encoding of * the private key may be PEM or DER.//from w ww .ja va 2s . c o m * * @param is * Stream to load the unencrypted private key from * @return The private key * @throws PrivateKeyEncryptedException * If private key is encrypted * @throws CryptoException * Problem encountered while loading the private key * @throws IOException * If an I/O error occurred */ public static PrivateKey load(InputStream is) throws CryptoException, IOException { byte[] streamContents = ReadUtil.readFully(is); // Check pkcs #8 is unencrypted EncryptionType encType = getEncryptionType(new ByteArrayInputStream(streamContents)); if (encType == null) { // Not a valid PKCS #8 private key throw new CryptoException(res.getString("NotValidPkcs8.exception.message")); } if (encType == ENCRYPTED) { throw new PrivateKeyEncryptedException(res.getString("Pkcs8IsEncrypted.exception.message")); } byte[] pvkBytes = null; // Check if stream is PEM encoded PemInfo pemInfo = PemUtil.decode(new ByteArrayInputStream(streamContents)); if (pemInfo != null) { // It is - get DER from PEM pvkBytes = pemInfo.getContent(); } /* * If we haven't got the key bytes via PEM then just use stream * contents directly (assume it is DER encoded) */ if (pvkBytes == null) { // Read in private key bytes pvkBytes = streamContents; } try { // Determine private key algorithm from key bytes String privateKeyAlgorithm = getPrivateKeyAlgorithm(pvkBytes); // Convert bytes to private key PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(pvkBytes); KeyFactory keyFactory = KeyFactory.getInstance(privateKeyAlgorithm); PrivateKey pvk = keyFactory.generatePrivate(privateKeySpec); return pvk; } catch (NoSuchAlgorithmException ex) { throw new CryptoException(res.getString("NoLoadPkcs8PrivateKey.exception.message"), ex); } catch (InvalidKeySpecException ex) { throw new CryptoException(res.getString("NoLoadPkcs8PrivateKey.exception.message"), ex); } }
From source file:com.zxy.commons.codec.rsa.RSAUtils.java
/** * <p>//from w w w . ja v a 2 s . c o m * ? * </p> * * @param data ?? * @param privateKey ?(BASE64?) * @return byte * @throws Exception Exception */ public static byte[] encryptByPrivateKey(byte[] data, String privateKey) throws Exception { byte[] keyBytes = Base64.decodeBase64(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.ENCRYPT_MODE, privateK); int inputLen = data.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int index = 0; // ? while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_ENCRYPT_BLOCK) { cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK); } else { cache = cipher.doFinal(data, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); index++; offSet = index * MAX_ENCRYPT_BLOCK; } byte[] encryptedData = out.toByteArray(); out.close(); return encryptedData; }
From source file:org.panbox.core.pairing.PAKCorePairingHandler.java
@Override public void runOperation(Cipher cipher, SecretKeySpec spec) throws Exception { CertificateFactory certificateFactory = CertificateFactory.getInstance(KeyConstants.CERTIFICATE_ENCODING); String sendbase64;//from w w w. j ava 2 s .c o m switch (pairingType) { case MASTER: logger.debug("PAKCorePairingHandler : runOperation : Started to handle MASTER pairing"); cipher.init(Cipher.ENCRYPT_MODE, spec); // master transmission logger.debug("PAKCorePairingHandler : runOperation : Will now send master/slave information..."); sendbase64 = Base64.encodeBase64String(cipher.doFinal( PairingType.MASTER.toString().getBytes(Charset.forName(PanboxConstants.STANDARD_CHARSET)))); dataOutputStream.writeObject(sendbase64); dataOutputStream.flush(); logger.debug("PAKCorePairingHandler : runOperation : Sent: " + sendbase64); // email, firstname, lastname, devicename transmission logger.debug("PAKCorePairingHandler : runOperation : Will now send personal information..."); sendbase64 = Base64.encodeBase64String( cipher.doFinal(eMail.getBytes(Charset.forName(PanboxConstants.STANDARD_CHARSET)))); dataOutputStream.writeObject(sendbase64); dataOutputStream.flush(); logger.debug("PAKCorePairingHandler : runOperation : Sent: " + sendbase64); sendbase64 = Base64.encodeBase64String( cipher.doFinal(firstName.getBytes(Charset.forName(PanboxConstants.STANDARD_CHARSET)))); dataOutputStream.writeObject(sendbase64); dataOutputStream.flush(); logger.debug("PAKCorePairingHandler : runOperation : Sent: " + sendbase64); sendbase64 = Base64.encodeBase64String( cipher.doFinal(lastName.getBytes(Charset.forName(PanboxConstants.STANDARD_CHARSET)))); dataOutputStream.writeObject(sendbase64); dataOutputStream.flush(); logger.debug("PAKCorePairingHandler : runOperation : Sent: " + sendbase64); sendbase64 = Base64.encodeBase64String( cipher.doFinal(deviceName.getBytes(Charset.forName(PanboxConstants.STANDARD_CHARSET)))); dataOutputStream.writeObject(sendbase64); dataOutputStream.flush(); logger.debug("PAKCorePairingHandler : runOperation : Sent: " + sendbase64); // owner privatekeys + password logger.debug("PAKCorePairingHandler : runOperation : Will now send owner privatekeys..."); sendbase64 = Base64.encodeBase64String(cipher.doFinal(Utils.toBytes(keyPassword))); Arrays.fill(keyPassword, '\u0000'); dataOutputStream.writeObject(sendbase64); dataOutputStream.flush(); logger.debug("PAKCorePairingHandler : runOperation : Sent: " + sendbase64); sendbase64 = Base64.encodeBase64String( cipher.doFinal(new PKCS8EncodedKeySpec(ownerKeyEnc.getEncoded()).getEncoded())); // This code can be inserted once Java 8 implements destroy-Method // in order to remove key material securely from JVM memory // try { // Destroyable destroyEncKey = ownerKeyEnc; // destroyEncKey.destroy(); // } catch (DestroyFailedException e1) { // logger.warn( // "PAKCorePairingHandler : runOperation : Could not destroy private enc key after pairing: ", // e1); // } dataOutputStream.writeObject(sendbase64); dataOutputStream.flush(); logger.debug("PAKCorePairingHandler : runOperation : Sent: " + sendbase64); sendbase64 = Base64.encodeBase64String( cipher.doFinal(new PKCS8EncodedKeySpec(ownerKeySign.getEncoded()).getEncoded())); // This code can be inserted once Java 8 implements destroy-Method // in order to remove key material securely from JVM memory // try { // Destroyable destroySignKey = ownerKeySign; // destroySignKey.destroy(); // } catch (DestroyFailedException e1) { // logger.warn( // "PAKCorePairingHandler : runOperation : Could not destroy private sign key after pairing: ", // e1); // } dataOutputStream.writeObject(sendbase64); dataOutputStream.flush(); logger.debug("PAKCorePairingHandler : runOperation : Sent: " + sendbase64); logger.debug("PAKCorePairingHandler : runOperation : Will now send known devices..."); sendbase64 = Base64.encodeBase64String(cipher.doFinal(Integer.toString(knownDevices.size()) .getBytes(Charset.forName(PanboxConstants.STANDARD_CHARSET)))); dataOutputStream.writeObject(sendbase64); dataOutputStream.flush(); logger.debug("PAKCorePairingHandler : runOperation : Sent numOfDevices: " + sendbase64); for (Map.Entry<String, X509Certificate> entry : knownDevices.entrySet()) { sendbase64 = Base64.encodeBase64String( cipher.doFinal(entry.getKey().getBytes(Charset.forName(PanboxConstants.STANDARD_CHARSET)))); dataOutputStream.writeObject(sendbase64); dataOutputStream.flush(); logger.debug("PAKCorePairingHandler : runOperation : Sent devicename: " + sendbase64); sendbase64 = Base64.encodeBase64String(cipher.doFinal(entry.getValue().getEncoded())); dataOutputStream.writeObject(sendbase64); dataOutputStream.flush(); logger.debug("PAKCorePairingHandler : runOperation : Sent devicecert: " + sendbase64); } logger.debug("PAKCorePairingHandler : runOperation : Will now send known contacts..."); File vcardFile = File.createTempFile("panbox-pairing-temp", null); AbstractAddressbookManager.exportContacts(knownContacts, vcardFile); sendbase64 = Base64 .encodeBase64String(cipher.doFinal(Files.readAllBytes(Paths.get(vcardFile.getAbsolutePath())))); dataOutputStream.writeObject(sendbase64); dataOutputStream.flush(); logger.debug("PAKCorePairingHandler : runOperation : Sent vcards: " + sendbase64); vcardFile.delete(); // transmission of devicetype and devicekey cipher.init(Cipher.DECRYPT_MODE, spec); String base64encRecDevType = (String) dataInputStream.readObject(); String base64encRecDevCert = (String) dataInputStream.readObject(); logger.debug("PAKCorePairingHandler : runOperation : Received devType: " + base64encRecDevType); logger.debug("PAKCorePairingHandler : runOperation : Received devCert: " + base64encRecDevCert); devType = DeviceType.valueOf(new String(cipher.doFinal(Base64.decodeBase64(base64encRecDevType)))); InputStream is = new ByteArrayInputStream(cipher.doFinal(Base64.decodeBase64(base64encRecDevCert))); devCert = (X509Certificate) certificateFactory.generateCertificate(is); break; case SLAVE: logger.debug("PAKCorePairingHandler : runOperation : Started to handle SLAVE pairing"); cipher.init(Cipher.ENCRYPT_MODE, spec); // slave transmission logger.debug("PAKCorePairingHandler : runOperation : Will now send master/slave information..."); sendbase64 = Base64.encodeBase64String(cipher.doFinal( PairingType.SLAVE.toString().getBytes(Charset.forName(PanboxConstants.STANDARD_CHARSET)))); dataOutputStream.writeObject(sendbase64); dataOutputStream.flush(); logger.debug("PAKCorePairingHandler : runOperation : Sent: " + sendbase64); // email, firstname, lastname, devicename transmission logger.debug("PAKCorePairingHandler : runOperation : Will now send personal information..."); sendbase64 = Base64.encodeBase64String( cipher.doFinal(eMail.getBytes(Charset.forName(PanboxConstants.STANDARD_CHARSET)))); dataOutputStream.writeObject(sendbase64); dataOutputStream.flush(); logger.debug("PAKCorePairingHandler : runOperation : Sent: " + sendbase64); sendbase64 = Base64.encodeBase64String( cipher.doFinal(firstName.getBytes(Charset.forName(PanboxConstants.STANDARD_CHARSET)))); dataOutputStream.writeObject(sendbase64); dataOutputStream.flush(); logger.debug("PAKCorePairingHandler : runOperation : Sent: " + sendbase64); sendbase64 = Base64.encodeBase64String( cipher.doFinal(lastName.getBytes(Charset.forName(PanboxConstants.STANDARD_CHARSET)))); dataOutputStream.writeObject(sendbase64); dataOutputStream.flush(); logger.debug("PAKCorePairingHandler : runOperation : Sent: " + sendbase64); sendbase64 = Base64.encodeBase64String( cipher.doFinal(deviceName.getBytes(Charset.forName(PanboxConstants.STANDARD_CHARSET)))); dataOutputStream.writeObject(sendbase64); dataOutputStream.flush(); logger.debug("PAKCorePairingHandler : runOperation : Sent: " + sendbase64); // owner certs logger.debug("PAKCorePairingHandler : runOperation : Will now send owner certificates..."); sendbase64 = Base64.encodeBase64String(cipher.doFinal(ownerCertEnc.getEncoded())); dataOutputStream.writeObject(sendbase64); dataOutputStream.flush(); logger.debug("PAKCorePairingHandler : runOperation : Sent: " + sendbase64); sendbase64 = Base64.encodeBase64String(cipher.doFinal(ownerCertSign.getEncoded())); dataOutputStream.writeObject(sendbase64); dataOutputStream.flush(); logger.debug("PAKCorePairingHandler : runOperation : Sent: " + sendbase64); logger.debug( "PAKCorePairingHandler : runOperation : Will now receive device information for device manager..."); logger.debug("PAKCorePairingHandler : runOperation : Will now send known devices..."); sendbase64 = Base64.encodeBase64String(cipher.doFinal(Integer.toString(knownDevices.size()) .getBytes(Charset.forName(PanboxConstants.STANDARD_CHARSET)))); dataOutputStream.writeObject(sendbase64); dataOutputStream.flush(); logger.debug("PAKCorePairingHandler : runOperation : Sent numOfDevices: " + sendbase64); for (Map.Entry<String, X509Certificate> entry : knownDevices.entrySet()) { sendbase64 = Base64.encodeBase64String( cipher.doFinal(entry.getKey().getBytes(Charset.forName(PanboxConstants.STANDARD_CHARSET)))); dataOutputStream.writeObject(sendbase64); dataOutputStream.flush(); logger.debug("PAKCorePairingHandler : runOperation : Sent devicename: " + sendbase64); sendbase64 = Base64.encodeBase64String(cipher.doFinal(entry.getValue().getEncoded())); dataOutputStream.writeObject(sendbase64); dataOutputStream.flush(); logger.debug("PAKCorePairingHandler : runOperation : Sent devicecert: " + sendbase64); } logger.debug("PAKCorePairingHandler : runOperation : Will now send known contacts..."); vcardFile = File.createTempFile("panbox-pairing-temp", null); AbstractAddressbookManager.exportContacts(knownContacts, vcardFile); sendbase64 = Base64 .encodeBase64String(cipher.doFinal(Files.readAllBytes(Paths.get(vcardFile.getAbsolutePath())))); dataOutputStream.writeObject(sendbase64); dataOutputStream.flush(); logger.debug("PAKCorePairingHandler : runOperation : Sent vcards: " + sendbase64); vcardFile.delete(); cipher.init(Cipher.DECRYPT_MODE, spec); // transmission of devicetype and devicekey base64encRecDevType = (String) dataInputStream.readObject(); base64encRecDevCert = (String) dataInputStream.readObject(); logger.debug("PAKCorePairingHandler : runOperation : Received devType: " + base64encRecDevType); logger.debug("PAKCorePairingHandler : runOperation : Received devCert: " + base64encRecDevCert); devType = DeviceType.valueOf(new String(cipher.doFinal(Base64.decodeBase64(base64encRecDevType)))); is = new ByteArrayInputStream(cipher.doFinal(Base64.decodeBase64(base64encRecDevCert))); devCert = (X509Certificate) certificateFactory.generateCertificate(is); break; default: } logger.debug("PAKCorePairingHandler : runOperation : Pairing finished. Will terminate session now."); closeConnection(); }
From source file:ie.peternagy.jcrypto.algo.EllipticCurveWrapper.java
/** * Try load the keys from disk// w w w . ja va 2s.co m */ public void tryLoadKeys() { try { byte[] publicBytes = Hex .decodeHex(new String(FileAccessUtil.readFromDisk(getKeyFilePath(false))).toCharArray()); byte[] privateBytes = Hex .decodeHex(new String(FileAccessUtil.readFromDisk(getKeyFilePath(true))).toCharArray()); KeyFactory fact = KeyFactory.getInstance("ECDSA", "BC"); publicKey = fact.generatePublic(new X509EncodedKeySpec(publicBytes)); privateKey = fact.generatePrivate(new PKCS8EncodedKeySpec(privateBytes)); } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidKeySpecException | DecoderException ex) { Logger.getLogger(EllipticCurveWrapper.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:org.kaaproject.kaa.common.endpoint.security.KeyUtil.java
/** * Gets the private key from bytes.//www .j av a 2 s . com * * @param keyBytes the key bytes * @return the private * @throws InvalidKeyException invalid key exception */ public static PrivateKey getPrivate(byte[] keyBytes) throws InvalidKeyException { try { PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory kf = KeyFactory.getInstance(RSA); return kf.generatePrivate(spec); } catch (NoSuchAlgorithmException | InvalidKeySpecException ex) { throw new InvalidKeyException(ex); } }
From source file:org.teknux.jettybootstrap.keystore.JettyKeystoreConvertorBuilder.java
public JettyKeystoreConvertorBuilder setPrivateKeyFromPKCS8(InputStream inputStream, String algorithm) throws JettyKeystoreException { try {/*ww w. ja v a 2s . co m*/ String contentKeyFile = IOUtils.toString(inputStream); Matcher contentKeyMatcher = PRIVATE_KEY_PATTERN.matcher(contentKeyFile); String contentKey; if (contentKeyMatcher.find()) { contentKey = contentKeyMatcher.group(1); } else { contentKey = contentKeyFile; } byte[] decodedKeyFile = Base64.decode(contentKey); KeyFactory keyFactory = KeyFactory.getInstance(algorithm); PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(decodedKeyFile); privateKey = keyFactory.generatePrivate(privateKeySpec); return this; } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException | DecoderException e) { throw new JettyKeystoreException(JettyKeystoreException.ERROR_LOAD_PRIVATE_KEY_PKCS8, "Can not load private key (PKCS8)", e); } }
From source file:org.oscarehr.common.hl7.v2.oscar_to_oscar.SendingUtils.java
/** * I know it returns a "private key" object but in reality it's a public key * because it's a key we give out to other people. *//*from ww w . j a va 2 s . com*/ public static PrivateKey getPublicServiceKey(String publicServiceKeyString) throws NoSuchAlgorithmException, InvalidKeySpecException { PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(publicServiceKeyString)); KeyFactory privKeyFactory = KeyFactory.getInstance("RSA"); PrivateKey publicServiceKey = privKeyFactory.generatePrivate(privKeySpec); return publicServiceKey; }
From source file:com.brienwheeler.apps.tomcat.TomcatBean.java
private RSAPrivateKey readKeyFile() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException { String parse[] = readPEMFile(sslKeyFile, KEY_PATTERN, 2); if (parse == null) throw new IllegalArgumentException("invalid key file contents"); if (parse[0].length() == 0) { // BEGIN PRIVATE KEY KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return (RSAPrivateKey) keyFactory.generatePrivate(new PKCS8EncodedKeySpec(Base64.decode(parse[1]))); }//from w w w .j av a 2 s . c o m if (parse[0].contains("RSA")) { // BEGIN RSA PRIVATE KEY Security.addProvider(new BouncyCastleProvider()); PEMParser pemParser = new PEMParser(new FileReader(sslKeyFile)); Object parsedObject = pemParser.readObject(); if (!(parsedObject instanceof PEMKeyPair)) throw new IllegalArgumentException("invalid key file contents"); PEMKeyPair keyPair = (PEMKeyPair) parsedObject; RSAPrivateKey privateKey = (RSAPrivateKey) BouncyCastleProvider .getPrivateKey(keyPair.getPrivateKeyInfo()); if (privateKey == null) throw new IllegalArgumentException("invalid key file contents"); return privateKey; } throw new IllegalArgumentException("invalid key file contents"); }
From source file:gemlite.core.util.RSAUtils.java
/** * <p>/*from w w w . j a v a 2 s . c o m*/ * ? * </p> * * @param data * ?? * @param privateKey * ?(BASE64?) * @return * @throws Exception */ public static byte[] encryptByPrivateKey(byte[] data, 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.ENCRYPT_MODE, privateK); int inputLen = data.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int i = 0; // ? while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_ENCRYPT_BLOCK) { cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK); } else { cache = cipher.doFinal(data, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * MAX_ENCRYPT_BLOCK; } byte[] encryptedData = out.toByteArray(); out.close(); return encryptedData; }