List of usage examples for java.security PublicKey getEncoded
public byte[] getEncoded();
From source file:com.tasktop.c2c.server.internal.profile.crypto.Rfc4716PublicKeyReader.java
/** * read a public key from the given text * /*w w w . j a v a 2 s. c o m*/ * @param keySpec * the key specification. * @return the key or null if no key was found */ public SshPublicKey readPublicKey(String keySpec) { BufferedReader reader = new BufferedReader(new StringReader(keySpec)); String line; SshPublicKey key = null; boolean endFound = false; boolean dataStarted = false; boolean continueHeader = false; String base64Data = ""; try { while ((line = reader.readLine()) != null) { line = line.trim(); // skip blank lines. They shouldn't really be in there, but if they are we can ignore them. if (line.length() != 0) { if (key == null) { if (line.equals(START_MARKER)) { key = new SshPublicKey(); } } else { if (line.equals(END_MARKER)) { endFound = true; break; } else if (!dataStarted && (continueHeader || HEADER_PATTERN.matcher(line).matches())) { // skip headers continueHeader = line.endsWith("\""); } else { dataStarted = true; base64Data += line; } } } } if (!endFound) { key = null; } else { if (base64Data.length() > 0) { byte[] keyData = Base64.decodeBase64(StringUtils.getBytesUtf8(base64Data)); Rfc4253Reader keyReader = new Rfc4253Reader(keyData, 0); String algorithm = keyReader.readString(); if ("ssh-rsa".equals(algorithm)) { key.setAlgorithm("RSA"); BigInteger exponent = keyReader.readMpint(); BigInteger modulus = keyReader.readMpint(); try { KeyFactory keyFactory = KeyFactory.getInstance(key.getAlgorithm()); RSAPublicKeySpec rsaPublicKeySpec = new RSAPublicKeySpec(modulus, exponent); PublicKey publicKey = keyFactory.generatePublic(rsaPublicKeySpec); byte[] encoded = publicKey.getEncoded(); key.setKeyData(encoded); } catch (InvalidKeySpecException t) { getLogger().warn("Invalid key spec: " + t.getMessage(), t); } catch (NoSuchAlgorithmException t) { getLogger().warn("Invalid algorithm: " + t.getMessage(), t); } } } } } catch (IOException e) { throw new IllegalStateException(e); } if (key == null || key.getAlgorithm() == null || key.getKeyData() == null) { key = null; } return key; }
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 va2 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:ch.cyberduck.core.sftp.PreferencesHostKeyVerifier.java
@Override public boolean verify(final String hostname, final int port, final PublicKey key) throws ConnectionCanceledException, ChecksumException { final String lookup = preferences.getProperty(this.getFormat(hostname, key)); if (StringUtils.equals(Base64.toBase64String(key.getEncoded()), lookup)) { if (log.isInfoEnabled()) { log.info(String.format("Accepted host key %s matching %s", key, lookup)); }//from www . j a v a 2s .c o m return true; } final boolean accept; if (null == lookup) { accept = this.isUnknownKeyAccepted(hostname, key); } else { accept = this.isChangedKeyAccepted(hostname, key); } return accept; }
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);/*ww w. jav a2s .co 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 storePublicKey(String path, PublicKey publicKey) { FileOutputStream fos = null;//ww w . j ava 2s . c om try { X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKey.getEncoded()); fos = new FileOutputStream(path); fos.write(x509EncodedKeySpec.getEncoded()); } catch (FileNotFoundException e) { LOG.error("Cannot save the public key to the specified path.", e); } catch (IOException e) { LOG.error("An I/O error occured while saving the public key", e); } finally { IOUtils.closeQuietly(fos); } }
From source file:com.google.appengine.tck.appidentity.AppIdentityServiceTest.java
@Test public void testGetPublicCertificates() throws Exception { Collection<PublicCertificate> certs = appIdentity.getPublicCertificatesForApp(); Assert.assertTrue("No certificates returned.", !certs.isEmpty()); for (PublicCertificate publicCert : certs) { Assert.assertTrue("No name for certificate.", !publicCert.getCertificateName().trim().isEmpty()); String pemFormat = publicCert.getX509CertificateInPemFormat(); String errMsg = "getX509CertificateInPemFormat():" + pemFormat; // TODO better check? Assert.assertTrue(errMsg, pemFormat.startsWith("-----BEGIN")); Assert.assertTrue(errMsg, pemFormat.contains("-----END")); InputStream stream = new ByteArrayInputStream( publicCert.getX509CertificateInPemFormat().getBytes("UTF-8")); CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate cert = cf.generateCertificate(stream); PublicKey pk = cert.getPublicKey(); Assert.assertNotNull(pk.getEncoded()); }/*from w w w . j av a 2 s . c o m*/ }
From source file:org.zaproxy.zap.extension.dynssl.SslCertificateUtils.java
/** * Creates a new Root CA certificate and returns private and public key as * {@link KeyStore}. The {@link KeyStore#getDefaultType()} is used. * * @return//from www . j av a 2 s.c om * @throws NoSuchAlgorithmException If no providers are found * for 'RSA' key pair generator * or 'SHA1PRNG' Secure random number generator * @throws IllegalStateException in case of errors during assembling {@link KeyStore} */ public static final KeyStore createRootCA() throws NoSuchAlgorithmException { final Date startDate = Calendar.getInstance().getTime(); final Date expireDate = new Date(startDate.getTime() + (DEFAULT_VALID_DAYS * 24L * 60L * 60L * 1000L)); final KeyPairGenerator g = KeyPairGenerator.getInstance("RSA"); g.initialize(2048, SecureRandom.getInstance("SHA1PRNG")); final KeyPair keypair = g.genKeyPair(); final PrivateKey privKey = keypair.getPrivate(); final PublicKey pubKey = keypair.getPublic(); Security.addProvider(new BouncyCastleProvider()); Random rnd = new Random(); // using the hash code of the user's name and home path, keeps anonymity // but also gives user a chance to distinguish between each other X500NameBuilder namebld = new X500NameBuilder(BCStyle.INSTANCE); namebld.addRDN(BCStyle.CN, "OWASP Zed Attack Proxy Root CA"); namebld.addRDN(BCStyle.L, Integer.toHexString(System.getProperty("user.name").hashCode()) + Integer.toHexString(System.getProperty("user.home").hashCode())); namebld.addRDN(BCStyle.O, "OWASP Root CA"); namebld.addRDN(BCStyle.OU, "OWASP ZAP Root CA"); namebld.addRDN(BCStyle.C, "xx"); X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(namebld.build(), BigInteger.valueOf(rnd.nextInt()), startDate, expireDate, namebld.build(), pubKey); KeyStore ks = null; try { certGen.addExtension(Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifier(pubKey.getEncoded())); certGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(true)); certGen.addExtension(Extension.keyUsage, false, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.cRLSign)); KeyPurposeId[] eku = { KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth, KeyPurposeId.anyExtendedKeyUsage }; certGen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(eku)); final ContentSigner sigGen = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider("BC") .build(privKey); final X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC") .getCertificate(certGen.build(sigGen)); ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(null, null); ks.setKeyEntry(SslCertificateService.ZAPROXY_JKS_ALIAS, privKey, SslCertificateService.PASSPHRASE, new Certificate[] { cert }); } catch (final Exception e) { throw new IllegalStateException("Errors during assembling root CA.", e); } return ks; }
From source file:com.zxy.commons.codec.rsa.AbstractRSAUtils.java
/** * ??/*from w ww . j av a2 s . c o m*/ * * @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:com.vmware.identity.openidconnect.sample.RelyingPartyInstaller.java
private void savePublicKey(String file, PublicKey publicKey) throws IOException { // Store Public Key. X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKey.getEncoded()); FileOutputStream fos = new FileOutputStream(file); fos.write(x509EncodedKeySpec.getEncoded()); fos.close();// w w w . j a va2 s . co m }
From source file:net.link.util.common.KeyUtils.java
public static X509Certificate generateCertificate(PublicKey subjectPublicKey, String subjectDn, PrivateKey issuerPrivateKey, @Nullable X509Certificate issuerCert, DateTime notBefore, DateTime notAfter, String inSignatureAlgorithm, boolean caCert, boolean timeStampingPurpose, @Nullable URI ocspUri) {//from w w w.j av a 2s. c o m try { String signatureAlgorithm = inSignatureAlgorithm; if (null == signatureAlgorithm) signatureAlgorithm = String.format("SHA1With%s", issuerPrivateKey.getAlgorithm()); X509Principal issuerDN; if (null != issuerCert) issuerDN = new X509Principal(issuerCert.getSubjectX500Principal().toString()); else issuerDN = new X509Principal(subjectDn); // new bc 2.0 API X509Principal subject = new X509Principal(subjectDn); SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(subjectPublicKey.getEncoded()); BigInteger serialNumber = new BigInteger(SERIALNUMBER_NUM_BITS, new SecureRandom()); X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder( X500Name.getInstance(issuerDN.toASN1Primitive()), serialNumber, notBefore.toDate(), notAfter.toDate(), X500Name.getInstance(subject.toASN1Primitive()), publicKeyInfo); // prepare signer ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm).build(issuerPrivateKey); certificateBuilder.addExtension(X509Extension.subjectKeyIdentifier, false, createSubjectKeyId(subjectPublicKey)); PublicKey issuerPublicKey; if (null != issuerCert) issuerPublicKey = issuerCert.getPublicKey(); else issuerPublicKey = subjectPublicKey; certificateBuilder.addExtension(X509Extension.authorityKeyIdentifier, false, createAuthorityKeyId(issuerPublicKey)); certificateBuilder.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(caCert)); if (timeStampingPurpose) certificateBuilder.addExtension(X509Extension.extendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_timeStamping)); if (null != ocspUri) { GeneralName ocspName = new GeneralName(GeneralName.uniformResourceIdentifier, ocspUri.toString()); AuthorityInformationAccess authorityInformationAccess = new AuthorityInformationAccess( X509ObjectIdentifiers.ocspAccessMethod, ocspName); certificateBuilder.addExtension(X509Extension.authorityInfoAccess, false, authorityInformationAccess); } // build return new JcaX509CertificateConverter().setProvider("BC") .getCertificate(certificateBuilder.build(signer)); } catch (CertificateException e) { throw new InternalInconsistencyException("X.509 is not supported.", e); } catch (OperatorCreationException e) { throw new InternalInconsistencyException(e); } catch (CertIOException e) { throw new InternalInconsistencyException(e); } }