List of usage examples for java.security.spec PKCS8EncodedKeySpec PKCS8EncodedKeySpec
public PKCS8EncodedKeySpec(byte[] encodedKey)
From source file:hudson.model.UsageStatisticsTest.java
/** * Makes sure that the stat data can be decrypted safely. *//*from w w w . j a v a 2 s .c om*/ public void testRoundtrip() throws Exception { // key pair for testing String privateKey = "30820276020100300d06092a864886f70d0101010500048202603082025c0201000281810084cababdb38040f659c2cb07a36d758f46e84ebc3d6ba39d967aedf1d396b0788ed3ab868d45ce280b1102b434c2a250ddc3254defe1785ab4f94d7038cf69ecca16753d2de3f6ad8976b3f74902d8634111d730982da74e1a6e3fc0bc3523bba53e45b8a8cbfd0321b94efc9f7fefbe66ad85281e3d0323d87f4426ec51204f0203010001028180784deaacdea8bd31f2d44578601954be3f714b93c2d977dbd76efb8f71303e249ad12dbeb2d2a1192a1d7923a6010768d7e06a3597b3df83de1d5688eb0f0e58c76070eddd696682730c93890dc727564c65dc8416bfbde5aad4eb7a97ed923efb55a291daf3c00810c0e43851298472fd539aab355af8cedcf1e9a0cbead661024100c498375102b068806c71dec838dc8dfa5624fb8a524a49cffadc19d10689a8c9c26db514faba6f96e50a605122abd3c9af16e82f2b7565f384528c9f31ea5947024100aceafd31d7f4872a873c7e5fe88f20c2fb086a053c6970026b3ce364768e2033100efb1ad8f2010fe53454a29decedc23a8a0c8df347742b1f13e11bd3a284b9024100931321470cd0f6cd24d4278bf8e61f9d69b6ef2bf3163a944aa340f91c7ffdf33aeea22b18cc43514af6714a21bb148d6cdca14530a8fa65acd7a8f62bfc9b5f024067452059f8438dc61466488336fce3f00ec483ad04db638dce45daf850e5a8cd5635dc39b87f2fab32940247ec5167ddabe06e870858104500967ac687aa73e102407e3b7997503e18d8d0f094d5e0bd5d57cb93cb39a2fc42cec1ea9a1562786438b61139e45813204d72c919f5397e139ad051d98e4d0f8a06d237f42c0d8440fb"; String publicKey = "30819f300d06092a864886f70d010101050003818d003081890281810084cababdb38040f659c2cb07a36d758f46e84ebc3d6ba39d967aedf1d396b0788ed3ab868d45ce280b1102b434c2a250ddc3254defe1785ab4f94d7038cf69ecca16753d2de3f6ad8976b3f74902d8634111d730982da74e1a6e3fc0bc3523bba53e45b8a8cbfd0321b94efc9f7fefbe66ad85281e3d0323d87f4426ec51204f0203010001"; String data = new UsageStatistics(publicKey).getStatData(); System.out.println(data); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PrivateKey priv = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(Util.fromHexString(privateKey))); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, priv); byte[] cipherText = Base64.decode(data.toCharArray()); InputStreamReader r = new InputStreamReader( new GZIPInputStream( new CombinedCipherInputStream(new ByteArrayInputStream(cipherText), cipher, "AES", 1024)), "UTF-8"); JSONObject o = JSONObject.fromObject(IOUtils.toString(r)); System.out.println(o); assertEquals(1, o.getInt("stat")); }
From source file:edu.vt.middleware.crypt.util.CryptReader.java
/** * Reads a DER-encoded private key in PKCS#8 format from an input stream into * a {@link PrivateKey} object. SSLeay-format keys may also work in some * cases; testing revealed SSLeay-format RSA keys generated by the OpenSSL rsa * command are supported.//ww w.ja v a 2 s . co m * * @param keyStream Input stream containing private key data. * @param algorithm Name of encryption algorithm used by key. * * @return Private key containing data read from stream. * * @throws CryptException On key format errors. * @throws IOException On key read errors. */ public static PrivateKey readPrivateKey(final InputStream keyStream, final String algorithm) throws CryptException, IOException { final KeyFactory kf = CryptProvider.getKeyFactory(algorithm); try { final PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(readData(keyStream)); return kf.generatePrivate(keysp); } catch (InvalidKeySpecException e) { throw new CryptException("Invalid private key format.", e); } }
From source file:io.kubernetes.client.util.SSLUtils.java
public static KeyStore createKeyStore(InputStream certInputStream, InputStream keyInputStream, String clientKeyAlgo, char[] clientKeyPassphrase, String keyStoreFile, char[] keyStorePassphrase) throws IOException, CertificateException, NoSuchAlgorithmException, InvalidKeySpecException, KeyStoreException {/*w w w . j a v a2s.c om*/ CertificateFactory certFactory = CertificateFactory.getInstance("X509"); X509Certificate cert = (X509Certificate) certFactory.generateCertificate(certInputStream); byte[] keyBytes = decodePem(keyInputStream); PrivateKey privateKey; KeyFactory keyFactory = KeyFactory.getInstance(clientKeyAlgo); try { // First let's try PKCS8 privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(keyBytes)); } catch (InvalidKeySpecException e) { // Otherwise try PKCS8 RSAPrivateCrtKeySpec keySpec = decodePKCS1(keyBytes); privateKey = keyFactory.generatePrivate(keySpec); } KeyStore keyStore = KeyStore.getInstance("JKS"); if (keyStoreFile != null && keyStoreFile.length() > 0) { keyStore.load(new FileInputStream(keyStoreFile), keyStorePassphrase); } else { loadDefaultKeyStoreFile(keyStore, keyStorePassphrase); } String alias = cert.getSubjectX500Principal().getName(); keyStore.setKeyEntry(alias, privateKey, clientKeyPassphrase, new Certificate[] { cert }); return keyStore; }
From source file:gemlite.core.util.RSAUtils.java
/** * <p>/*from w ww . ja v a 2 s . c o m*/ * ????? * </p> * * @param data * ? * @param privateKey * ?(BASE64?) * * @return * @throws Exception */ public static String sign(byte[] data, String privateKey) throws Exception { byte[] keyBytes = Base64Utils.decode(privateKey); PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec); Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM); signature.initSign(privateK); signature.update(data); return Base64Utils.encode(signature.sign()); }
From source file:de.pawlidi.openaletheia.utils.CipherUtils.java
/** * //from w w w .ja v a 2 s .c o m * @param data * @return */ public static RSAPrivateKey buildPrivateKey(final String key) { if (StringUtils.isNotEmpty(key)) { try { byte[] bytes = Converter.toBytes(key); KeyFactory keyFactory = KeyFactory.getInstance(CIPHER_ALGORITHM); PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(bytes); return (RSAPrivateKey) keyFactory.generatePrivate(privSpec); } catch (Exception e) { throw new RuntimeException("Cannot create " + CIPHER_ALGORITHM + " private key from " + key, e); } } return null; }
From source file:org.apache.kerby.pkix.PkiLoader.java
private PrivateKey doLoadPrivateKey(InputStream inputStream, String password) throws GeneralSecurityException, IOException { if (password == null) { password = ""; }/* www . j a va2 s . co m*/ // If the provided InputStream is encrypted, we need a password to decrypt // it. If the InputStream is not encrypted, then the password is ignored // (can be null). The InputStream can be DER (raw ASN.1) or PEM (base64). PKCS8Key pkcs8 = new PKCS8Key(inputStream, password.toCharArray()); // If an unencrypted PKCS8 key was provided, then this actually returns // exactly what was originally passed inputStream (with no changes). If an OpenSSL // key was provided, it gets reformatted as PKCS #8 first, and so these // bytes will still be PKCS #8, not OpenSSL. byte[] decrypted = pkcs8.getDecryptedBytes(); PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decrypted); // A Java PrivateKey object is born. PrivateKey pk = null; if (pkcs8.isDSA()) { pk = KeyFactory.getInstance("DSA").generatePrivate(spec); } else if (pkcs8.isRSA()) { pk = KeyFactory.getInstance("RSA").generatePrivate(spec); } // For lazier types: pk = pkcs8.getPrivateKey(); return pk; }
From source file:org.springframework.security.oauth.common.signature.RSAKeySecret.java
/** * Creates a private key from the PKCS#8-encoded value of the given bytes. * * @param privateKey The PKCS#8-encoded private key bytes. * @return The private key.//w ww.jav a2s . co m */ public static PrivateKey createPrivateKey(byte[] privateKey) { if (privateKey == null) { return null; } try { KeyFactory fac = KeyFactory.getInstance("RSA"); EncodedKeySpec spec = new PKCS8EncodedKeySpec(privateKey); return fac.generatePrivate(spec); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); } catch (InvalidKeySpecException e) { throw new IllegalStateException(e); } }
From source file:com.cws.esolutions.security.dao.keymgmt.impl.FileKeyManager.java
/** * @see com.cws.esolutions.security.dao.keymgmt.interfaces.KeyManager#returnKeys(java.lang.String) *///from w w w. j a va2 s . c o m public synchronized KeyPair returnKeys(final String guid) throws KeyManagementException { final String methodName = FileKeyManager.CNAME + "#returnKeys(final String guid) throws KeyManagementException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("Value: {}", guid); } KeyPair keyPair = null; InputStream pubStream = null; InputStream privStream = null; final File keyDirectory = FileUtils.getFile(keyConfig.getKeyDirectory() + "/" + guid); try { if (!(keyDirectory.exists())) { throw new KeyManagementException("Configured key directory does not exist and unable to create it"); } File publicFile = FileUtils .getFile(keyDirectory + "/" + guid + SecurityServiceConstants.PUBLICKEY_FILE_EXT); File privateFile = FileUtils .getFile(keyDirectory + "/" + guid + SecurityServiceConstants.PRIVATEKEY_FILE_EXT); if ((publicFile.exists()) && (privateFile.exists())) { privStream = new FileInputStream(privateFile); byte[] privKeyBytes = IOUtils.toByteArray(privStream); pubStream = new FileInputStream(publicFile); byte[] pubKeyBytes = IOUtils.toByteArray(pubStream); // files exist KeyFactory keyFactory = KeyFactory.getInstance(keyConfig.getKeyAlgorithm()); // generate private key PKCS8EncodedKeySpec privateSpec = new PKCS8EncodedKeySpec(privKeyBytes); PrivateKey privKey = keyFactory.generatePrivate(privateSpec); // generate pubkey X509EncodedKeySpec publicSpec = new X509EncodedKeySpec(pubKeyBytes); PublicKey pubKey = keyFactory.generatePublic(publicSpec); // make the keypair keyPair = new KeyPair(pubKey, privKey); } else { // files dont exist throw new KeyManagementException("Failed to locate user keys"); } } catch (FileNotFoundException fnfx) { throw new KeyManagementException(fnfx.getMessage(), fnfx); } catch (InvalidKeySpecException iksx) { throw new KeyManagementException(iksx.getMessage(), iksx); } catch (IOException iox) { throw new KeyManagementException(iox.getMessage(), iox); } catch (NoSuchAlgorithmException nsax) { throw new KeyManagementException(nsax.getMessage(), nsax); } finally { if (privStream != null) { IOUtils.closeQuietly(privStream); } if (pubStream != null) { IOUtils.closeQuietly(pubStream); } } return keyPair; }
From source file:com.cloud.utils.security.CertificateHelper.java
public static Key buildPrivateKey(String base64EncodedKeyContent) throws NoSuchAlgorithmException, InvalidKeySpecException, IOException { KeyFactory kf = KeyFactory.getInstance("RSA"); PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(Base64.decodeBase64(base64EncodedKeyContent)); return kf.generatePrivate(keysp); }
From source file:org.ejbca.ui.cli.ca.CaImportCVCCACommand.java
public void execute(String[] args) throws ErrorAdminCommandException { if (args.length < 4) { getLogger().info("Description: " + getDescription()); getLogger().info(/* w w w.j a va 2 s .c om*/ "Usage 1: " + getCommand() + " <CA name> <pkcs8 RSA private key file> <certificate file>"); getLogger().info(" Imports a private key and a self signed CVCA certificate and creates a CVCA."); getLogger().info("Usage 2: " + getCommand() + " <CA name> <pkcs8 private key file> <certificate file> <DN of form C=country,CN=mnemonic,SERIALNUMBER=sequence> <signatureAlgorithm> <validity days>"); getLogger().info( " Imports a private key and generates a new self signed CVCA certificate with the given DN and creates a CVCA."); getLogger().info( " Signature algorithm can be SHA1WithRSA, SHA256WithRSA, SHA1WithECDSA, SHA224WithECDSA, SHA256WithECDSA, etc."); getLogger().info( " SERIALNUMBER will not be a part of the CAs DN, it is only used to set a specified sequence (should be of form 00001). Can be left out, and a random sequence is then generated."); return; } try { String caName = args[1]; String pkFile = args[2]; String certFile = args[3]; // Import key and certificate CryptoProviderTools.installBCProvider(); byte[] pkbytes = FileTools.readFiletoBuffer(pkFile); PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(pkbytes); KeyFactory keyfact = KeyFactory.getInstance("RSA", "BC"); // Doesn't matter if we say RSA here, it will fix an EC key as well PrivateKey privKey = keyfact.generatePrivate(spec); byte[] certbytes = FileTools.readFiletoBuffer(certFile); Certificate cert = null; try { // First check if it was a PEM formatted certificate Collection<Certificate> certs = CertTools.getCertsFromPEM(new ByteArrayInputStream(certbytes)); cert = certs.iterator().next(); } catch (IOException e) { // This was not a PEM certificate, I hope it's binary... cert = CertTools.getCertfromByteArray(certbytes); } PublicKey pubKey = cert.getPublicKey(); // Verify that the public and private key belongs together getLogger().info("Testing keys with algorithm: " + pubKey.getAlgorithm()); KeyTools.testKey(privKey, pubKey, null); Certificate cacert = null; if (args.length > 6) { // Create a self signed CVCA cert from the DN getLogger().info("Generating new self signed certificate."); String dn = args[4]; String sigAlg = args[5]; Integer valdays = Integer.parseInt(args[6]); String country = CertTools.getPartFromDN(dn, "C"); String mnemonic = CertTools.getPartFromDN(dn, "CN"); String seq = CertTools.getPartFromDN(dn, "SERIALNUMBER"); if (StringUtils.isEmpty(seq)) { seq = RandomStringUtils.randomNumeric(5); getLogger().info("No sequence given, using random 5 number sequence: " + seq); } HolderReferenceField holderRef = new HolderReferenceField(country, mnemonic, seq); CAReferenceField caRef = new CAReferenceField(holderRef.getCountry(), holderRef.getMnemonic(), holderRef.getSequence()); AuthorizationRoleEnum authRole = AuthorizationRoleEnum.CVCA; Date notBefore = new Date(); Calendar notAfter = Calendar.getInstance(); notAfter.add(Calendar.DAY_OF_MONTH, valdays); CVCertificate cvc = CertificateGenerator.createCertificate(pubKey, privKey, sigAlg, caRef, holderRef, authRole, AccessRightEnum.READ_ACCESS_DG3_AND_DG4, notBefore, notAfter.getTime(), "BC"); cacert = new CardVerifiableCertificate(cvc); } else { getLogger().info("Using passed in self signed certificate."); cacert = cert; } try { cacert.verify(pubKey); } catch (SignatureException e) { getLogger().info("Can not verify self signed certificate: " + e.getMessage()); System.exit(3); // NOPMD } Certificate[] chain = new Certificate[1]; chain[0] = cacert; ejb.getCAAdminSession().importCAFromKeys(getAdmin(), caName, "foo123", chain, pubKey, privKey, null, null); } catch (ErrorAdminCommandException e) { throw e; } catch (Exception e) { throw new ErrorAdminCommandException(e); } }