List of usage examples for java.security.spec PKCS8EncodedKeySpec PKCS8EncodedKeySpec
public PKCS8EncodedKeySpec(byte[] encodedKey)
From source file:org.psl.fidouaf.core.crypto.KeyCodec.java
public static PrivateKey getPrivKey(byte[] bytes) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException { KeyFactory kf = KeyFactory.getInstance("ECDSA", "BC"); return kf.generatePrivate(new PKCS8EncodedKeySpec(bytes)); }
From source file:org.apache.james.jdkim.IscheduleDKIMSigner.java
/** * Generate a PrivateKey from a Base64 encoded private key. * * In order to generate a valid PKCS8 key when you have a PEM key you can do * this: <code>//from w ww . java 2 s. c o m * openssl pkcs8 -topk8 -inform PEM -in rsapriv.pem -outform DER -nocrypt -out rsapriv.der * </code> And then base64 encode the content. * * @param privateKeyPKCS8 * a Base64 encoded string of the RSA key in PKCS8 format * @return the PrivateKey * @throws NoSuchAlgorithmException * if RSA is unknown * @throws InvalidKeySpecException * on bad input key */ public static PrivateKey getPrivateKey(final String privateKeyPKCS8) throws NoSuchAlgorithmException, InvalidKeySpecException { byte[] encKey = Base64.decodeBase64(privateKeyPKCS8.getBytes()); // byte[] encKey = privateKey.getBytes(); PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(encKey); KeyFactory keyFactory; keyFactory = KeyFactory.getInstance("RSA"); PrivateKey privKey = keyFactory.generatePrivate(privSpec); return privKey; }
From source file:org.apache.james.jdkim.DKIMSigner.java
/** * Generate a PrivateKey from a Base64 encoded private key. * //w w w. j av a2 s . co m * In order to generate a valid PKCS8 key when you have a PEM key you can do * this: <code> * openssl pkcs8 -topk8 -inform PEM -in rsapriv.pem -outform DER -nocrypt -out rsapriv.der * </code> And then base64 encode the content. * * @param privateKeyPKCS8 * a Base64 encoded string of the RSA key in PKCS8 format * @return the PrivateKey * @throws NoSuchAlgorithmException * if RSA is unknown * @throws InvalidKeySpecException * on bad input key */ public static PrivateKey getPrivateKey(String privateKeyPKCS8) throws NoSuchAlgorithmException, InvalidKeySpecException { byte[] encKey = Base64.decodeBase64(privateKeyPKCS8.getBytes()); // byte[] encKey = privateKey.getBytes(); PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(encKey); KeyFactory keyFactory; keyFactory = KeyFactory.getInstance("RSA"); PrivateKey privKey = keyFactory.generatePrivate(privSpec); return privKey; }
From source file:org.tolven.session.OpenAMSessionWrapper.java
@Override public PrivateKey getUserPrivateKey(String keyAlgorithm) { String userPKCS8EncodedKey = null; try {/* w w w . jav a2s. c o m*/ userPKCS8EncodedKey = getSsoToken().getProperty("userPKCS8EncodedKey"); } catch (Exception ex) { throw new RuntimeException("Could not get userPKCS8EncodedKey from SSOToken", ex); } if (userPKCS8EncodedKey == null) { return null; } else { try { byte[] userPKCS8EncodedKeyBytes = userPKCS8EncodedKey.getBytes("UTF-8"); PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec( Base64.decodeBase64(userPKCS8EncodedKeyBytes)); return getKeyFactory(keyAlgorithm).generatePrivate(pkcs8EncodedKeySpec); } catch (Exception ex) { throw new RuntimeException("Could not get PrivateKey from pkcs8EncodedKey", ex); } } }
From source file:com.kuzumeji.platform.standard.SecurityService.java
/** * RSA??/* ww w . j a va 2 s . c o m*/ * <dl> * <dt>? * <dd>RSA?? * </dl> * @param name RSA??? * @return RSA? */ public KeyPair loadKeyPair(final String name) { try { final Properties property = new PropertyService(PROPERTY_NAME).getProperty(); final KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGO_NAME); final RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(new X509EncodedKeySpec( Hex.decodeHex(property.getProperty(String.format(KEY_PUBLIC_ENCODED, name)).toCharArray()))); final RSAPrivateKey privateKey = (RSAPrivateKey) keyFactory.generatePrivate(new PKCS8EncodedKeySpec( Hex.decodeHex(property.getProperty(String.format(KEY_PRIVATE_ENCODED, name)).toCharArray()))); return new KeyPair(publicKey, privateKey); } catch (final IOException | DecoderException | InvalidKeySpecException | NoSuchAlgorithmException e) { throw new RuntimeException(e); } }
From source file:org.apache.ofbiz.base.util.KeyStoreUtil.java
public static void importPKCS8CertChain(KeyStore ks, String alias, byte[] keyBytes, String keyPass, byte[] certChain) throws InvalidKeySpecException, NoSuchAlgorithmException, CertificateException, KeyStoreException { // load the private key KeyFactory kf = KeyFactory.getInstance("RSA"); PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(keyBytes); PrivateKey pk = kf.generatePrivate(keysp); // load the cert chain CertificateFactory cf = CertificateFactory.getInstance("X.509"); ByteArrayInputStream bais = new ByteArrayInputStream(certChain); Collection<? extends Certificate> certCol = cf.generateCertificates(bais); Certificate[] certs = new Certificate[certCol.toArray().length]; if (certCol.size() == 1) { Debug.logInfo("Single certificate; no chain", module); bais = new ByteArrayInputStream(certChain); Certificate cert = cf.generateCertificate(bais); certs[0] = cert;/*from w ww .ja va 2 s .co m*/ } else { Debug.logInfo("Certificate chain length : " + certCol.size(), module); certs = certCol.toArray(new Certificate[certCol.size()]); } ks.setKeyEntry(alias, pk, keyPass.toCharArray(), certs); }
From source file:org.panbox.core.pairing.PAKCorePairingRequester.java
@Override public void runOperation(Cipher cipher, SecretKeySpec spec) throws Exception { logger.debug("PAKCorePairingHandler : runOperation : Started to request pairing"); KeyFactory keyFactory = KeyFactory.getInstance(KeyConstants.ASYMMETRIC_ALGORITHM_ALGO_ONLY); CertificateFactory certificateFactory = CertificateFactory.getInstance(KeyConstants.CERTIFICATE_ENCODING); cipher.init(Cipher.DECRYPT_MODE, spec); String base64received;// w w w . j a va 2 s. c o m base64received = (String) dataInputStream.readObject(); logger.debug("PAKCorePairingRequester : runOperation : Received pairingType: " + base64received); byte[] encType = Base64.decodeBase64(base64received); String strType = new String(cipher.doFinal(encType)); type = PairingType.valueOf(strType); switch (type) { case MASTER: logger.info("PAKCorePairingRequester : runOperation : This device will be paired as master device!"); base64received = (String) dataInputStream.readObject(); logger.debug("PAKCorePairingRequester : runOperation : Received email: " + base64received); eMail = new String(cipher.doFinal(Base64.decodeBase64(base64received))); base64received = (String) dataInputStream.readObject(); logger.debug("PAKCorePairingRequester : runOperation : Received firstname: " + base64received); firstName = new String(cipher.doFinal(Base64.decodeBase64(base64received))); base64received = (String) dataInputStream.readObject(); logger.debug("PAKCorePairingRequester : runOperation : Received lastname: " + base64received); lastName = new String(cipher.doFinal(Base64.decodeBase64(base64received))); base64received = (String) dataInputStream.readObject(); logger.debug("PAKCorePairingRequester : runOperation : Received devicename: " + base64received); deviceName = new String(cipher.doFinal(Base64.decodeBase64(base64received))); base64received = (String) dataInputStream.readObject(); logger.debug("PAKCorePairingRequester : runOperation : Received keyPassword: " + base64received); keyPassword = Utils.toChars(cipher.doFinal(Base64.decodeBase64(base64received))); base64received = (String) dataInputStream.readObject(); logger.debug("PAKCorePairingRequester : runOperation : Received ownerKeyEnc: " + base64received); PKCS8EncodedKeySpec ownerKeyEncSpec = new PKCS8EncodedKeySpec( cipher.doFinal(Base64.decodeBase64(base64received))); PrivateKey pKey = keyFactory.generatePrivate(ownerKeyEncSpec); ownerKeyEnc = CryptCore.privateKeyToKeyPair(pKey); base64received = (String) dataInputStream.readObject(); logger.debug("PAKCorePairingRequester : runOperation : Received ownerKeySign: " + base64received); PKCS8EncodedKeySpec ownerKeySignSpec = new PKCS8EncodedKeySpec( cipher.doFinal(Base64.decodeBase64(base64received))); pKey = keyFactory.generatePrivate(ownerKeySignSpec); ownerKeySign = CryptCore.privateKeyToKeyPair(pKey); base64received = (String) dataInputStream.readObject(); logger.debug("PAKCorePairingRequester : runOperation : Received numOfDevices: " + base64received); int numOfDevices = Integer.valueOf(new String(cipher.doFinal(Base64.decodeBase64(base64received)))); knownDevices = new HashMap<String, X509Certificate>(); for (int i = 0; i < numOfDevices; ++i) { base64received = (String) dataInputStream.readObject(); logger.debug("PAKCorePairingRequester : runOperation : Received device name (" + i + "): " + base64received); String knownDeviceName = new String(cipher.doFinal(Base64.decodeBase64(base64received))); base64received = (String) dataInputStream.readObject(); logger.debug("PAKCorePairingRequester : runOperation : Received device certificate (" + i + "): " + base64received); InputStream is = new ByteArrayInputStream(cipher.doFinal(Base64.decodeBase64(base64received))); X509Certificate knownDeviceCert = (X509Certificate) certificateFactory.generateCertificate(is); knownDevices.put(knownDeviceName, knownDeviceCert); logger.debug("PAKCorePairingRequester : runOperation : Added device (" + i + "): " + knownDeviceName + ": " + knownDeviceCert); } base64received = (String) dataInputStream.readObject(); logger.debug("PAKCorePairingRequester : runOperation : Received contacts: " + base64received); InputStream is = new ByteArrayInputStream(cipher.doFinal(Base64.decodeBase64(base64received))); knownContacts = Ezvcard.parse(is).all(); // --- SEND Device Type and Key --- cipher.init(Cipher.ENCRYPT_MODE, spec); byte[] encDevType = cipher.doFinal(devType.toString().getBytes()); devCert = CryptCore.createSelfSignedX509Certificate(devKey.getPrivate(), devKey.getPublic(), new PairingIPersonDummy(eMail, firstName, lastName)); byte[] encDevCert = cipher.doFinal(devCert.getEncoded()); String base64encDevType = Base64.encodeBase64String(encDevType); String base64encDevCert = Base64.encodeBase64String(encDevCert); logger.debug("PAKCorePairingRequester : runOperation : Send devicetype: " + base64encDevType); logger.debug("PAKCorePairingRequester : runOperation : Send devicecert: " + base64encDevCert); dataOutputStream.writeObject(base64encDevType); dataOutputStream.flush(); dataOutputStream.writeObject(base64encDevCert); dataOutputStream.flush(); break; case SLAVE: logger.info("PAKCorePairingRequester : runOperation : This device will be paired as slave device!"); base64received = (String) dataInputStream.readObject(); logger.debug("PAKCorePairingRequester : runOperation : Received email: " + base64received); eMail = new String(cipher.doFinal(Base64.decodeBase64(base64received))); base64received = (String) dataInputStream.readObject(); logger.debug("PAKCorePairingRequester : runOperation : Received firstname: " + base64received); firstName = new String(cipher.doFinal(Base64.decodeBase64(base64received))); base64received = (String) dataInputStream.readObject(); logger.debug("PAKCorePairingRequester : runOperation : Received lastname: " + base64received); lastName = new String(cipher.doFinal(Base64.decodeBase64(base64received))); base64received = (String) dataInputStream.readObject(); logger.debug("PAKCorePairingRequester : runOperation : Received devicename: " + base64received); deviceName = new String(cipher.doFinal(Base64.decodeBase64(base64received))); base64received = (String) dataInputStream.readObject(); logger.debug("PAKCorePairingRequester : runOperation : Received ownerCertEnc: " + base64received); is = new ByteArrayInputStream(cipher.doFinal(Base64.decodeBase64(base64received))); ownerCertEnc = (X509Certificate) certificateFactory.generateCertificate(is); base64received = (String) dataInputStream.readObject(); logger.debug("PAKCorePairingRequester : runOperation : Received ownerCertSign: " + base64received); is = new ByteArrayInputStream(cipher.doFinal(Base64.decodeBase64(base64received))); ownerCertSign = (X509Certificate) certificateFactory.generateCertificate(is); base64received = (String) dataInputStream.readObject(); logger.debug("PAKCorePairingRequester : runOperation : Received numOfDevices: " + base64received); numOfDevices = Integer.valueOf(new String(cipher.doFinal(Base64.decodeBase64(base64received)))); knownDevices = new HashMap<String, X509Certificate>(); for (int i = 0; i < numOfDevices; ++i) { base64received = (String) dataInputStream.readObject(); logger.debug("PAKCorePairingRequester : runOperation : Received device name (" + i + "): " + base64received); String knownDeviceName = new String(cipher.doFinal(Base64.decodeBase64(base64received))); base64received = (String) dataInputStream.readObject(); logger.debug("PAKCorePairingRequester : runOperation : Received device certificate (" + i + "): " + base64received); is = new ByteArrayInputStream(cipher.doFinal(Base64.decodeBase64(base64received))); X509Certificate knownDeviceCert = (X509Certificate) certificateFactory.generateCertificate(is); knownDevices.put(knownDeviceName, knownDeviceCert); logger.debug("PAKCorePairingRequester : runOperation : Added device (" + i + "): " + knownDeviceName + ": " + knownDeviceCert); } base64received = (String) dataInputStream.readObject(); logger.debug("PAKCorePairingRequester : runOperation : Received contacts: " + base64received); is = new ByteArrayInputStream(cipher.doFinal(Base64.decodeBase64(base64received))); knownContacts = Ezvcard.parse(is).all(); // --- SEND Device Type and Key --- cipher.init(Cipher.ENCRYPT_MODE, spec); encDevType = cipher.doFinal(devType.toString().getBytes()); devCert = CryptCore.createSelfSignedX509Certificate(devKey.getPrivate(), devKey.getPublic(), new PairingIPersonDummy(eMail, firstName, lastName)); encDevCert = cipher.doFinal(devCert.getEncoded()); base64encDevType = Base64.encodeBase64String(encDevType); base64encDevCert = Base64.encodeBase64String(encDevCert); logger.debug("PAKCorePairingRequester : runOperation : Send devicetype: " + base64encDevType); logger.debug("PAKCorePairingRequester : runOperation : Send devicecert: " + base64encDevCert); dataOutputStream.writeObject(base64encDevType); dataOutputStream.flush(); dataOutputStream.writeObject(base64encDevCert); dataOutputStream.flush(); break; default: logger.error("PAKCorePairingRequester : runOperation : Unknown pairing type!"); break; } logger.debug( "PAKCorePairingRequester : runOperation : Pairing finished. Will wait for session to be closed!."); try { dataInputStream.readBoolean(); } catch (Exception ex) { // Connection has been closed successfully! Pairing done :) } }
From source file:com.shenit.commons.codec.RsaUtils.java
/** * ?/* w w w . j a va2s.co m*/ * * @param key * ?base64? * @throws Exception */ public static PrivateKey getPrivateKey(String key) throws Exception { byte[] keyBytes; keyBytes = Base64.decodeBase64(key); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(CODEC_RSA); PrivateKey privateKey = keyFactory.generatePrivate(keySpec); return privateKey; }
From source file:org.apache.xml.security.test.encryption.BaltimoreEncTest.java
/** * Method setUp//from ww w .j a v a2s. co m */ protected void setUp() throws Exception { // Create the comparison strings DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setAttribute("http://xml.org/sax/features/namespaces", Boolean.TRUE); String filename = "data/ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml"; String basedir = System.getProperty("basedir"); if (basedir != null && !"".equals(basedir)) { filename = basedir + "/" + filename; } File f = new File(filename); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(new java.io.FileInputStream(f)); cardNumber = retrieveCCNumber(doc); // Test decrypt testDecryptString = new String("top secret message\n"); // Count the nodes in the document as a secondary test nodeCount = countNodes(doc); // Create the keys jebBytes = "abcdefghijklmnopqrstuvwx".getBytes("ASCII"); jobBytes = "abcdefghijklmnop".getBytes("ASCII"); jedBytes = "abcdefghijklmnopqrstuvwxyz012345".getBytes("ASCII"); // Certificate information rsaCertSerialNumber = new String("1014918766910"); // rsaKey filename = "data/ie/baltimore/merlin-examples/merlin-xmlenc-five/rsa.p8"; if (basedir != null && !"".equals(basedir)) { filename = basedir + "/" + filename; } byte[] pkcs8Bytes = JavaUtils.getBytesFromFile(filename); PKCS8EncodedKeySpec pkcs8Spec = new PKCS8EncodedKeySpec(pkcs8Bytes); // Create a key factory KeyFactory keyFactory = KeyFactory.getInstance("RSA"); rsaKey = keyFactory.generatePrivate(pkcs8Spec); // Initialise the library org.apache.xml.security.Init.init(); // Register our key resolver KeyResolver.register("org.apache.xml.security.test.encryption.BobKeyResolver"); // Check what algorithms are available haveISOPadding = false; String algorithmId = JCEMapper .translateURItoJCEID(org.apache.xml.security.utils.EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128); if (algorithmId != null) { try { if (Cipher.getInstance(algorithmId) != null) haveISOPadding = true; } catch (NoSuchAlgorithmException nsae) { } catch (NoSuchPaddingException nspe) { } } haveKeyWraps = (JCEMapper.translateURItoJCEID( org.apache.xml.security.utils.EncryptionConstants.ALGO_ID_KEYWRAP_AES128) != null); }
From source file:com.turo.pushy.apns.auth.ApnsSigningKey.java
/** * Loads a signing key from the given input stream. * * @param inputStream the input stream from which to load the key * @param teamId the ten-character, Apple-issued identifier for the team to which the key belongs * @param keyId the ten-character, Apple-issued identitifier for the key itself * * @return an APNs signing key with the given key ID and associated with the given team * * @throws IOException if a key could not be loaded from the given file for any reason * @throws NoSuchAlgorithmException if the JVM does not support elliptic curve keys * @throws InvalidKeyException if the loaded key is invalid for any reason *///from w w w.jav a2 s. c o m public static ApnsSigningKey loadFromInputStream(final InputStream inputStream, final String teamId, final String keyId) throws IOException, NoSuchAlgorithmException, InvalidKeyException { final ECPrivateKey signingKey; { final String base64EncodedPrivateKey; { final StringBuilder privateKeyBuilder = new StringBuilder(); final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); boolean haveReadHeader = false; boolean haveReadFooter = false; for (String line; (line = reader.readLine()) != null;) { if (!haveReadHeader) { if (line.contains("BEGIN PRIVATE KEY")) { haveReadHeader = true; } } else { if (line.contains("END PRIVATE KEY")) { haveReadFooter = true; break; } else { privateKeyBuilder.append(line); } } } if (!(haveReadHeader && haveReadFooter)) { throw new IOException("Could not find private key header/footer"); } base64EncodedPrivateKey = privateKeyBuilder.toString(); } final byte[] keyBytes = Base64.decodeBase64(base64EncodedPrivateKey); final PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes); final KeyFactory keyFactory = KeyFactory.getInstance("EC"); try { signingKey = (ECPrivateKey) keyFactory.generatePrivate(keySpec); } catch (InvalidKeySpecException e) { throw new InvalidKeyException(e); } } return new ApnsSigningKey(keyId, teamId, signingKey); }