List of usage examples for java.security PublicKey getEncoded
public byte[] getEncoded();
From source file:org.apache.nifi.registry.security.util.CertificateUtils.java
/** * Generates an issued {@link X509Certificate} from the given issuer certificate and {@link KeyPair} * * @param dn the distinguished name to use * @param publicKey the public key to issue the certificate to * @param extensions extensions extracted from the CSR * @param issuer the issuer's certificate * @param issuerKeyPair the issuer's keypair * @param signingAlgorithm the signing algorithm to use * @param days the number of days it should be valid for * @return an issued {@link X509Certificate} from the given issuer certificate and {@link KeyPair} * @throws CertificateException if there is an error issuing the certificate *//*from w ww . ja v a2 s . com*/ public static X509Certificate generateIssuedCertificate(String dn, PublicKey publicKey, Extensions extensions, X509Certificate issuer, KeyPair issuerKeyPair, String signingAlgorithm, int days) throws CertificateException { try { ContentSigner sigGen = new JcaContentSignerBuilder(signingAlgorithm) .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(issuerKeyPair.getPrivate()); SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()); Date startDate = new Date(); Date endDate = new Date(startDate.getTime() + TimeUnit.DAYS.toMillis(days)); X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder( reverseX500Name(new X500Name(issuer.getSubjectX500Principal().getName())), getUniqueSerialNumber(), startDate, endDate, reverseX500Name(new X500Name(dn)), subPubKeyInfo); certBuilder.addExtension(Extension.subjectKeyIdentifier, false, new JcaX509ExtensionUtils().createSubjectKeyIdentifier(publicKey)); certBuilder.addExtension(Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(issuerKeyPair.getPublic())); // Set certificate extensions // (1) digitalSignature extension certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyAgreement | KeyUsage.nonRepudiation)); certBuilder.addExtension(Extension.basicConstraints, false, new BasicConstraints(false)); // (2) extendedKeyUsage extension certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage( new KeyPurposeId[] { KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth })); // (3) subjectAlternativeName if (extensions != null && extensions.getExtension(Extension.subjectAlternativeName) != null) { certBuilder.addExtension(Extension.subjectAlternativeName, false, extensions.getExtensionParsedValue(Extension.subjectAlternativeName)); } X509CertificateHolder certificateHolder = certBuilder.build(sigGen); return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME) .getCertificate(certificateHolder); } catch (CertIOException | NoSuchAlgorithmException | OperatorCreationException e) { throw new CertificateException(e); } }
From source file:be.fedict.eid.idp.model.admin.AdminManagerBean.java
private String getId(X509Certificate certificate) { PublicKey publicKey = certificate.getPublicKey(); return DigestUtils.shaHex(publicKey.getEncoded()); }
From source file:ch.cyberduck.core.sftp.PreferencesHostKeyVerifier.java
@Override protected void allow(final String hostname, final PublicKey key, final boolean persist) { if (persist) { preferences.setProperty(this.getFormat(hostname, key), Base64.toBase64String(key.getEncoded())); }/*from w w w. ja v a 2s . c om*/ }
From source file:com.bluepixel.security.manager.Server.java
private void generateKey() { try {/*from w ww .j av a 2 s. c o m*/ KeyPairGenerator keyGen = KeyPairGenerator.getInstance(DEFAULT_ALGORITHM); keyGen.initialize(DEFAULT_KEY_LENGTH); KeyPair keypair = keyGen.generateKeyPair(); PublicKey pbKey = keypair.getPublic(); PrivateKey piKey = keypair.getPrivate(); publicKey = Base64.encodeWebSafe(pbKey.getEncoded(), false); privateKey = Base64.encodeWebSafe(piKey.getEncoded(), false); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, piKey); secretKeys = new ConcurrentHashMap<String, String>(); String[] randomKeys = generateRandomWords(10); for (String key : randomKeys) { String cipherText = Base64.encodeWebSafe(cipher.doFinal(key.getBytes()), false); secretKeys.put(key, cipherText); } } catch (NoSuchAlgorithmException e) { } catch (InvalidKeyException e) { } catch (NoSuchPaddingException e) { } catch (IllegalBlockSizeException e) { } catch (BadPaddingException e) { } }
From source file:org.gluu.com.ox_push2.u2f.v2.cert.KeyPairGeneratorImpl.java
@Override public byte[] encodePublicKey(PublicKey publicKey) { byte[] encodedWithPadding = publicKey.getEncoded(); byte[] encoded = new byte[65]; System.arraycopy(encodedWithPadding, 26, encoded, 0, encoded.length); if (BuildConfig.DEBUG) Log.d(TAG, "Encoded public key: " + Utils.encodeHexString(encoded)); return encoded; }
From source file:com.tasktop.c2c.server.internal.profile.crypto.OpenSSHPublicKeyReader.java
public SshPublicKey readPublicKey(String keySpec) { keySpec = keySpec.trim();/*from www .j a va 2s . com*/ String[] parts = keySpec.split(" "); if (parts.length >= 2) { String algorithm = parts[0]; String base64Data = parts[1]; if (algorithm.equals("ssh-rsa")) { SshPublicKey sshPublicKey = new SshPublicKey(); sshPublicKey.setAlgorithm("RSA"); byte[] decodedData = Base64.decodeBase64(StringUtils.getBytesUtf8(base64Data)); Rfc4253Reader reader = new Rfc4253Reader(decodedData, 0); try { byte[] format = reader.readBytes(); byte[] exponent = reader.readBytes(); byte[] modulus = reader.readBytes(); if (Arrays.equals(FORMAT, format)) { BigInteger exp = new BigInteger(exponent); BigInteger mod = new BigInteger(modulus); RSAPublicKeySpec rsaPublicKeySpec = new RSAPublicKeySpec(mod, exp); try { PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(rsaPublicKeySpec); sshPublicKey.setKeyData(publicKey.getEncoded()); return sshPublicKey; } catch (InvalidKeySpecException t) { getLogger().warn("Invalid key spec: " + t.getMessage(), t); } catch (NoSuchAlgorithmException t) { getLogger().warn("Invalid algorithm: " + t.getMessage(), t); } } } catch (IOException e) { // ignore } } } return null; }
From source file:org.apache.sshd.client.keyverifier.RequiredServerKeyVerifier.java
public boolean verifyServerKey(ClientSession sshClientSession, SocketAddress remoteAddress, PublicKey serverKey) { if (requiredKey.equals(serverKey)) { return true; }/*w ww . j a va 2 s . c o m*/ log.info("Server at " + remoteAddress + " presented wrong key: " + BufferUtils.printHex(serverKey.getEncoded())); return false; }
From source file:be.fedict.eid.applet.beta.admin.AdministratorServiceBean.java
private void register(PublicKey publicKey, String serialNumber) { AdministratorEntity administratorEntity = new AdministratorEntity(); administratorEntity.setPublicKey(publicKey.getEncoded()); administratorEntity.setSerialNumber(serialNumber); this.entityManager.persist(administratorEntity); }
From source file:net.link.util.test.pkix.PkiTestUtils.java
public static X509Certificate generateCertificate(PublicKey subjectPublicKey, String subjectDn, PrivateKey issuerPrivateKey, @Nullable X509Certificate issuerCert, DateTime notBefore, DateTime notAfter, @Nullable String signatureAlgorithm, boolean includeAuthorityKeyIdentifier, boolean caCert, boolean timeStampingPurpose, @Nullable URI ocspUri) throws IOException, CertificateException, OperatorCreationException { String finalSignatureAlgorithm = signatureAlgorithm; if (null == signatureAlgorithm) finalSignatureAlgorithm = "SHA512WithRSAEncryption"; X509Principal issuerDN;//from w w w. j a v a 2 s . c o m 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(finalSignatureAlgorithm).build(issuerPrivateKey); // add extensions certificateBuilder.addExtension(X509Extension.subjectKeyIdentifier, false, createSubjectKeyId(subjectPublicKey)); PublicKey issuerPublicKey; if (null != issuerCert) issuerPublicKey = issuerCert.getPublicKey(); else issuerPublicKey = subjectPublicKey; if (includeAuthorityKeyIdentifier) 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, new DERIA5String(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)); }
From source file:org.ejbca.util.keystore.KeyTools.java
/** * create the subject key identifier./*from ww w.j a v a 2 s.co m*/ * * @param pubKey the public key * * @return SubjectKeyIdentifer asn.1 structure */ public static SubjectKeyIdentifier createSubjectKeyId(final PublicKey pubKey) { try { final ASN1Sequence keyASN1Sequence; final Object keyObject = new ASN1InputStream(new ByteArrayInputStream(pubKey.getEncoded())) .readObject(); if (keyObject instanceof ASN1Sequence) { keyASN1Sequence = (ASN1Sequence) keyObject; } else { // PublicKey key that don't encode to a ASN1Sequence. Fix this by creating a BC object instead. final PublicKey altKey = (PublicKey) KeyFactory.getInstance(pubKey.getAlgorithm(), "BC") .translateKey(pubKey); keyASN1Sequence = (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(altKey.getEncoded())) .readObject(); } return new SubjectKeyIdentifier(new SubjectPublicKeyInfo(keyASN1Sequence)); } catch (Exception e) { final RuntimeException e2 = new RuntimeException("error creating key"); // NOPMD e2.initCause(e); throw e2; } }