List of usage examples for java.security PrivateKey getEncoded
public byte[] getEncoded();
From source file:vellum.cryptostore.RsaStoreTest.java
public void testGenerate(int iterationCount) throws Exception { long millis = System.currentTimeMillis(); RsaKeyStore ks = new RsaKeyStore(); ks.generate(alias, keySize);/*from ww w . j a v a 2 s. co m*/ ByteArrayOutputStream kos = new ByteArrayOutputStream(); ks.storePublic(kos); ByteArrayInputStream kis = new ByteArrayInputStream(kos.toByteArray()); PublicKey loadedPublicKey = ks.loadPublic(kis); System.out.printf("loaded public key %s %s: %s\n", alias, loadedPublicKey.getAlgorithm(), Base64.encodeBase64String(loadedPublicKey.getEncoded())); assertTrue("loaded public key", Arrays.equals(ks.getKeyPair().getPublic().getEncoded(), loadedPublicKey.getEncoded())); ByteArrayOutputStream baos = new ByteArrayOutputStream(); new RsaStore().store(baos, type, alias, text.getBytes(), ks.getKeyPair().getPublic()); millis = Millis.elapsed(millis); System.out.printf("store %s %d %dms: %s\n", alias, iterationCount, millis, text); millis = System.currentTimeMillis(); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); kos = new ByteArrayOutputStream(); ks.storePrivate(kos, password); kis = new ByteArrayInputStream(kos.toByteArray()); PrivateKey loadedPrivateKey = ks.loadPrivate(kis, alias, password); assertTrue("loaded private key", Arrays.equals(ks.getKeyPair().getPrivate().getEncoded(), loadedPrivateKey.getEncoded())); millis = Millis.elapsed(millis); System.out.printf("loaded private key %s %d %dms: %s\n", alias, iterationCount, millis, loadedPrivateKey.getAlgorithm()); millis = System.currentTimeMillis(); byte[] loadBytes = new RsaStore().load(bais, type, alias, loadedPrivateKey); millis = Millis.elapsed(millis); System.out.printf("load %s %d %dms: %s\n", alias, iterationCount, millis, new String(loadBytes)); assertTrue("loaded bytes", Arrays.equals(loadBytes, text.getBytes())); }
From source file:com.zxy.commons.codec.rsa.AbstractRSAUtils.java
/** * ??/*from w ww . j a va 2 s . c om*/ * * @param pubFile public file * @param priFile private file * @throws IOException IOException */ @SuppressWarnings("PMD.PrematureDeclaration") protected void generater(File pubFile, File priFile) throws IOException { try { KeyPairGenerator keygen = KeyPairGenerator.getInstance(ALGORITHM); SecureRandom secrand = new SecureRandom(); keygen.initialize(KEY_SIZE, secrand); KeyPair keys = keygen.genKeyPair(); PublicKey pubkey = keys.getPublic(); PrivateKey prikey = keys.getPrivate(); byte[] priKey = Base64.encodeBase64(prikey.getEncoded()); byte[] pubKey = Base64.encodeBase64(pubkey.getEncoded()); if (pubFile.exists()) { throw new IOException(pubFile.getPath() + " is exist!"); } if (priFile.exists()) { throw new IOException(priFile.getPath() + " is exist!"); } OutputStream pubOutput = new FileOutputStream(pubFile); try { IOUtils.write(pubKey, pubOutput); } finally { IOUtils.closeQuietly(pubOutput); } OutputStream priOutput = new FileOutputStream(priFile); try { IOUtils.write(priKey, priOutput); } finally { IOUtils.closeQuietly(priOutput); } } catch (NoSuchAlgorithmException e) { log.error("?", e); } }
From source file:org.sonatype.sisu.encryptor.RsaAesEncryptor.java
public void generateKeys(OutputStream publicKeyOut, OutputStream privateKeyOut) throws GeneralSecurityException, IOException { KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); generator.initialize(KEY_SIZE * 8, random); KeyPair keyPair = generator.generateKeyPair(); OutputStream privateOut = new Base64OutputStream(privateKeyOut); PrivateKey privateKey = keyPair.getPrivate(); privateOut.write(privateKey.getEncoded()); IOUtil.close(privateOut);// w w w. ja v a 2 s. c o m OutputStream publicOut = new Base64OutputStream(publicKeyOut); PublicKey publicKey = keyPair.getPublic(); publicOut.write(publicKey.getEncoded()); IOUtil.close(publicOut); }
From source file:com.buzzcoders.security.cryptoutils.asymmetric.AbstractAsymmetricEncryptionModule.java
public void storePrivateKey(String path, PrivateKey privateKey) { FileOutputStream fos = null;//from www . j ava 2 s . co m try { PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded()); fos = new FileOutputStream(path); fos.write(pkcs8EncodedKeySpec.getEncoded()); } catch (FileNotFoundException e) { LOG.error("Cannot save the private key to the specified path.", e); } catch (IOException e) { LOG.error("An I/O error occured while saving the private key", e); } finally { IOUtils.closeQuietly(fos); } }
From source file:org.cogroo.addon.util.SecurityUtil.java
/** * Encrypt data using an key encrypted with a private key. * @param privateKey the private key to decrypt the secret key * @param encryptedSecretKey a encrypted secret key * @param data the data to encrypt/*ww w . j ava 2s . c o m*/ * @return the encrypted data * @throws InvalidKeyException one of the keys is invalid */ public byte[] encrypt(PrivateKey privateKey, byte[] encryptedSecretKey, String data) throws InvalidKeyException { byte[] encryptedData = null; try { byte[] chave = privateKey.getEncoded(); // Decrypt secret symmetric key with private key Cipher rsacf = Cipher.getInstance("RSA"); rsacf.init(Cipher.DECRYPT_MODE, privateKey); byte[] secretKey = rsacf.doFinal(encryptedSecretKey); encryptedData = encrypt(secretKey, data); } catch (Exception e) { LOG.log(Level.SEVERE, "Exception encrypting data", e); } return encryptedData; }
From source file:test.integ.be.e_contract.mycarenet.etee.SealTest.java
@Test public void testSeal() throws Exception { InputStream sealInputStream = SealTest.class.getResourceAsStream("/seal-fcorneli.der"); assertNotNull(sealInputStream);//from w ww .j a va 2 s.com byte[] cmsData = IOUtils.toByteArray(sealInputStream); // check outer signature byte[] data = getVerifiedContent(cmsData); // decrypt content CMSEnvelopedDataParser cmsEnvelopedDataParser = new CMSEnvelopedDataParser(data); LOG.debug("content encryption algo: " + cmsEnvelopedDataParser.getContentEncryptionAlgorithm().getAlgorithm().getId()); RecipientInformationStore recipientInformationStore = cmsEnvelopedDataParser.getRecipientInfos(); Collection<RecipientInformation> recipients = recipientInformationStore.getRecipients(); RecipientInformation recipientInformation = recipients.iterator().next(); LOG.debug("recipient info type: " + recipientInformation.getClass().getName()); KeyTransRecipientInformation keyTransRecipientInformation = (KeyTransRecipientInformation) recipientInformation; // load eHealth encryption certificate KeyStore eHealthKeyStore = KeyStore.getInstance("PKCS12"); FileInputStream fileInputStream = new FileInputStream(this.config.getEHealthPKCS12Path()); eHealthKeyStore.load(fileInputStream, this.config.getEHealthPKCS12Password().toCharArray()); Enumeration<String> aliasesEnum = eHealthKeyStore.aliases(); aliasesEnum.nextElement(); // skip authentication certificate. String alias = aliasesEnum.nextElement(); X509Certificate eHealthCertificate = (X509Certificate) eHealthKeyStore.getCertificate(alias); PrivateKey eHealthPrivateKey = (PrivateKey) eHealthKeyStore.getKey(alias, this.config.getEHealthPKCS12Password().toCharArray()); AsymmetricKeyParameter privKeyParams = PrivateKeyFactory.createKey(eHealthPrivateKey.getEncoded()); BcRSAKeyTransEnvelopedRecipient recipient = new BcRSAKeyTransEnvelopedRecipient(privKeyParams); byte[] decryptedContent = recipientInformation.getContent(recipient); assertNotNull(decryptedContent); LOG.debug("decrypted content size: " + decryptedContent.length); byte[] result = getVerifiedContent(decryptedContent); LOG.debug("result: " + new String(result)); }
From source file:com.vmware.identity.openidconnect.sample.RelyingPartyInstaller.java
private void savePrivateKey(String file, PrivateKey privateKey) throws IOException { // Store Private Key. PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded()); FileOutputStream fos = new FileOutputStream(file); fos.write(pkcs8EncodedKeySpec.getEncoded()); fos.close();/*w w w.ja v a 2 s .c om*/ }
From source file:org.globus.gsi.bc.BouncyCastleOpenSSLKey.java
protected byte[] getEncoded(PrivateKey key) { String format = key.getFormat(); if (format != null && (format.equalsIgnoreCase("PKCS#8") || format.equalsIgnoreCase("PKCS8"))) { try {// w ww.j ava 2s . c o m ASN1Primitive keyInfo = BouncyCastleUtil.toASN1Primitive(key.getEncoded()); PrivateKeyInfo pkey = new PrivateKeyInfo((ASN1Sequence) keyInfo); ASN1Primitive derKey = pkey.getPrivateKey(); return BouncyCastleUtil.toByteArray(derKey); } catch (IOException e) { // that should never happen logger.warn("This shouldn't have happened.", e); return new byte[] {}; } } else if (format != null && format.equalsIgnoreCase("PKCS#1") && key instanceof RSAPrivateCrtKey) { // this condition will rarely be true RSAPrivateCrtKey pKey = (RSAPrivateCrtKey) key; RSAPrivateKeyStructure st = new RSAPrivateKeyStructure(pKey.getModulus(), pKey.getPublicExponent(), pKey.getPrivateExponent(), pKey.getPrimeP(), pKey.getPrimeQ(), pKey.getPrimeExponentP(), pKey.getPrimeExponentQ(), pKey.getCrtCoefficient()); ASN1Primitive ob = st.toASN1Primitive(); try { return BouncyCastleUtil.toByteArray(ob); } catch (IOException e) { // that should never happen return new byte[0]; } } else { return new byte[0]; } }
From source file:com.owncloud.android.util.EncryptionTestIT.java
@Test public void encryptPrivateKey() throws Exception { String keyPhrase = "moreovertelevisionfactorytendencyindependenceinternationalintellectualimpress" + "interestvolunteer"; KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(4096, new SecureRandom()); KeyPair keyPair = keyGen.generateKeyPair(); PrivateKey privateKey = keyPair.getPrivate(); byte[] privateKeyBytes = privateKey.getEncoded(); String privateKeyString = EncryptionUtils.encodeBytesToBase64String(privateKeyBytes); String encryptedString = EncryptionUtils.encryptPrivateKey(privateKeyString, keyPhrase); String decryptedString = EncryptionUtils.decryptPrivateKey(encryptedString, keyPhrase); assertEquals(privateKeyString, decryptedString); }
From source file:org.wso2.tools.ksexplorer.action.ShowPEMPrivateKeyAction.java
public String execute() throws Exception { HttpServletRequest request = (HttpServletRequest) ActionContext.getContext() .get(StrutsStatics.HTTP_REQUEST); HttpSession session = request.getSession(); List keyStoreDescriptions = (List) session.getAttribute(KSExplorerConstants.SESSION_KEY_KS); String ksId = request.getParameter("ksId"); KeyStoreDescription ksDesc = null;//from w ww .j av a2 s .co m for (Iterator iterator = keyStoreDescriptions.iterator(); iterator.hasNext();) { KeyStoreDescription desc = (KeyStoreDescription) iterator.next(); if (desc.getUuid().equals(ksId)) { ksDesc = desc; } } KeyStore store = ksDesc.getKeyStore(); this.storeName = ksDesc.getName(); this.alias = request.getParameter("alias"); String keyPasswd = request.getParameter("keyPasswd"); PrivateKey key = (PrivateKey) store.getKey(alias, keyPasswd.toCharArray()); log.info("[WSO2KSE] : Showing key : " + alias + " in keystore : " + this.storeName + " (store id :" + ksId + ")"); BASE64Encoder encoder = new BASE64Encoder(); pemKey = "-----BEGIN PRIVATE KEY-----\n"; pemKey += encoder.encode(key.getEncoded()); pemKey += "\n-----END PRIVATE KEY-----"; return SUCCESS; }