List of usage examples for java.security KeyFactory generatePrivate
public final PrivateKey generatePrivate(KeySpec keySpec) throws InvalidKeySpecException
From source file:bftsmart.reconfiguration.util.RSAKeyLoader.java
private PrivateKey getPrivateKeyFromString(String key) throws Exception { KeyFactory keyFactory = KeyFactory.getInstance("RSA"); EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(key)); PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec); return privateKey; }
From source file:RGSDigestTools.SignatureTool.java
public void initKeysWithFiles(String PrivkeyResource, String PubkeyResource) throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException, UnrecoverableEntryException, InvalidKeySpecException { // KeyStore ks = TrustStoreLoader.loadKeyStore(pKeyStorePath,pKeyStorePasswd); // KeyStore.PasswordProtection passProtection = new KeyStore.PasswordProtection(pPrivKeyPasswd.toCharArray()); // KeyStore.PrivateKeyEntry DSKeyEnt = (KeyStore.PrivateKeyEntry)ks.getEntry(pDSAlias, passProtection); // //from w ww . ja v a 2 s . co m InputStream is_piv = SignatureTool.class.getResourceAsStream(PrivkeyResource); ByteArrayOutputStream baos_priv = new ByteArrayOutputStream(); int read_priv = is_piv.read(); while (read_priv != -1) { baos_priv.write(read_priv); read_priv = is_piv.read(); } byte[] keyBytes_priv = baos_priv.toByteArray(); PKCS8EncodedKeySpec spec_pkcs8 = new PKCS8EncodedKeySpec(keyBytes_priv); KeyFactory keyFactoryPriv = KeyFactory.getInstance("RSA"); this.signKey = keyFactoryPriv.generatePrivate(spec_pkcs8); // this.signKey = DSKeyEnt.getPrivateKey(); InputStream is = SignatureTool.class.getResourceAsStream(PubkeyResource); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int read = is.read(); while (read != -1) { baos.write(read); read = is.read(); } byte[] keyBytes = baos.toByteArray(); X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); this.verifyKey = keyFactory.generatePublic(spec); }
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;/*w w w .ja v a2s.c o m*/ 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:org.ejbca.util.keystore.KeyTools.java
/** * Creates PKCS12-file that can be imported in IE or Firefox. The alias for the private key is * set to 'privateKey' and the private key password is null. * * @param alias the alias used for the key entry * @param privKey RSA private key//from w w w .j a va 2 s .c o m * @param cert user certificate * @param cachain CA-certificate chain or null if only one cert in chain, in that case use 'cert'. * @return KeyStore containing PKCS12-keystore * @exception Exception if input parameters are not OK or certificate generation fails */ public static KeyStore createP12(final String alias, final PrivateKey privKey, final Certificate cert, final Certificate[] cachain) throws IOException, KeyStoreException, CertificateException, NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException { if (log.isTraceEnabled()) { log.trace(">createP12: alias=" + alias + ", privKey, cert=" + CertTools.getSubjectDN(cert) + ", cachain.length=" + ((cachain == null) ? 0 : cachain.length)); } // Certificate chain if (cert == null) { throw new IllegalArgumentException("Parameter cert cannot be null."); } int len = 1; if (cachain != null) { len += cachain.length; } final Certificate[] chain = new Certificate[len]; // To not get a ClassCastException we need to generate a real new certificate with BC final CertificateFactory cf = CertTools.getCertificateFactory(); chain[0] = cf.generateCertificate(new ByteArrayInputStream(cert.getEncoded())); if (cachain != null) { for (int i = 0; i < cachain.length; i++) { final X509Certificate tmpcert = (X509Certificate) cf .generateCertificate(new ByteArrayInputStream(cachain[i].getEncoded())); chain[i + 1] = tmpcert; } } if (chain.length > 1) { for (int i = 1; i < chain.length; i++) { final X509Certificate cacert = (X509Certificate) cf .generateCertificate(new ByteArrayInputStream(chain[i].getEncoded())); // Set attributes on CA-cert try { final PKCS12BagAttributeCarrier caBagAttr = (PKCS12BagAttributeCarrier) chain[i]; // We construct a friendly name for the CA, and try with some parts from the DN if they exist. String cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "CN"); // On the ones below we +i to make it unique, O might not be otherwise if (cafriendly == null) { cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "O") + i; } if (cafriendly == null) { cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "OU" + i); } if (cafriendly == null) { cafriendly = "CA_unknown" + i; } caBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(cafriendly)); } catch (ClassCastException e) { log.error("ClassCastException setting BagAttributes, can not set friendly name: ", e); } } } // Set attributes on user-cert try { final PKCS12BagAttributeCarrier certBagAttr = (PKCS12BagAttributeCarrier) chain[0]; certBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(alias)); // in this case we just set the local key id to that of the public key certBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, createSubjectKeyId(chain[0].getPublicKey())); } catch (ClassCastException e) { log.error("ClassCastException setting BagAttributes, can not set friendly name: ", e); } // "Clean" private key, i.e. remove any old attributes final KeyFactory keyfact = KeyFactory.getInstance(privKey.getAlgorithm(), "BC"); final PrivateKey pk = keyfact.generatePrivate(new PKCS8EncodedKeySpec(privKey.getEncoded())); // Set attributes for private key try { final PKCS12BagAttributeCarrier keyBagAttr = (PKCS12BagAttributeCarrier) pk; // in this case we just set the local key id to that of the public key keyBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(alias)); keyBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, createSubjectKeyId(chain[0].getPublicKey())); } catch (ClassCastException e) { log.error("ClassCastException setting BagAttributes, can not set friendly name: ", e); } // store the key and the certificate chain final KeyStore store = KeyStore.getInstance("PKCS12", "BC"); store.load(null, null); store.setKeyEntry(alias, pk, null, chain); if (log.isTraceEnabled()) { log.trace("<createP12: alias=" + alias + ", privKey, cert=" + CertTools.getSubjectDN(cert) + ", cachain.length=" + ((cachain == null) ? 0 : cachain.length)); } return store; }
From source file:org.xdi.oxauth.model.jws.RSASigner.java
@Override public String generateSignature(String signingInput) throws SignatureException { if (getSignatureAlgorithm() == null) { throw new SignatureException("The signature algorithm is null"); }//from www.ja v a 2 s . co m if (rsaPrivateKey == null) { throw new SignatureException("The RSA private key is null"); } if (signingInput == null) { throw new SignatureException("The signing input is null"); } try { RSAPrivateKeySpec rsaPrivateKeySpec = new RSAPrivateKeySpec(rsaPrivateKey.getModulus(), rsaPrivateKey.getPrivateExponent()); KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC"); PrivateKey privateKey = keyFactory.generatePrivate(rsaPrivateKeySpec); Signature signature = Signature.getInstance(getSignatureAlgorithm().getAlgorithm(), "BC"); signature.initSign(privateKey); signature.update(signingInput.getBytes(Util.UTF8_STRING_ENCODING)); return JwtUtil.base64urlencode(signature.sign()); } catch (InvalidKeySpecException e) { throw new SignatureException(e); } catch (InvalidKeyException e) { throw new SignatureException(e); } catch (NoSuchAlgorithmException e) { throw new SignatureException(e); } catch (NoSuchProviderException e) { throw new SignatureException(e); } catch (SignatureException e) { throw new SignatureException(e); } catch (UnsupportedEncodingException e) { throw new SignatureException(e); } catch (Exception e) { throw new SignatureException(e); } }
From source file:com.teasoft.teavote.util.Signature.java
private PrivateKey getPrivateKey() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException { Resource resource = res.getResource("classpath:xormeSafui"); byte[] privKeyBytes; try (InputStream privKeyInputStream = resource.getInputStream()) { privKeyBytes = IOUtils.toByteArray(privKeyInputStream); privKeyBytes = Base64.decodeBase64(privKeyBytes); }/*from w ww .ja v a 2 s . c o m*/ PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(privKeyBytes); KeyFactory keyFactory = KeyFactory.getInstance("DSA"); PrivateKey privKey = keyFactory.generatePrivate(privKeySpec); return privKey; }
From source file:org.casbah.provider.PKCS1EncodedKeyTest.java
@Before public void setup() throws GeneralSecurityException { KeyFactory kf = KeyFactory.getInstance("RSA"); RSAPrivateCrtKeySpec keyspec = new RSAPrivateCrtKeySpec(MODULUS, PUBLIC_EXPONENT, PRIVATE_EXPONENT, PRIME1, PRIME2, EXPONENT1, EXPONENT2, COEFFICIENT); wrappedKey = (RSAPrivateCrtKey) kf.generatePrivate(keyspec); }
From source file:org.sonatype.sisu.encryptor.RsaAesEncryptor.java
protected PrivateKey readPrivateKey(InputStream keyInput) throws IOException, GeneralSecurityException { InputStream input = new Base64InputStream(keyInput); byte[] encKey = IOUtil.toByteArray(input); IOUtil.close(input);/* w ww. ja va 2s. c o m*/ PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encKey); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec); return privateKey; }
From source file:com.cedarsoft.crypt.CertTest.java
@Test public void testKey() throws Exception { InputStream inStream = new DataInputStream(getClass().getResource("/test.der").openStream()); byte[] keyBytes = new byte[inStream.available()]; inStream.read(keyBytes);//from w w w.j av a 2s .co m inStream.close(); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); // decipher private key PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(keyBytes); RSAPrivateKey privKey = (RSAPrivateKey) keyFactory.generatePrivate(privSpec); assertNotNull(privKey); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, privKey); byte[] bytes = cipher.doFinal(PLAINTEXT.getBytes()); assertEquals(SCRAMBLED, new String(Base64.encodeBase64(bytes))); }
From source file:architecture.common.license.LicenseSigner.java
protected void init(Reader keyReader) throws IOException, NoSuchAlgorithmException, DecoderException, InvalidKeySpecException, InvalidKeyException { BufferedReader in = new BufferedReader(keyReader); String privateKey = in.readLine(); in.close();/*from w w w . jav a 2 s . c o m*/ KeyFactory keyFactory = KeyFactory.getInstance("DSA"); sig = Signature.getInstance("SHA1withDSA"); PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(Hex.decodeHex(privateKey.toCharArray())); java.security.PrivateKey privKey = keyFactory.generatePrivate(privKeySpec); sig.initSign(privKey); }