Java Code Examples for org.bouncycastle.asn1.x509.SubjectPublicKeyInfo
The following examples show how to use
org.bouncycastle.asn1.x509.SubjectPublicKeyInfo.
These examples are extracted from open source projects.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: keycloak Author: keycloak File: CertificateUtils.java License: Apache License 2.0 | 6 votes |
public static X509Certificate generateV1SelfSignedCertificate(KeyPair caKeyPair, String subject, BigInteger serialNumber) { try { X500Name subjectDN = new X500Name("CN=" + subject); Date validityStartDate = new Date(System.currentTimeMillis() - 100000); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.YEAR, 10); Date validityEndDate = new Date(calendar.getTime().getTime()); SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(caKeyPair.getPublic().getEncoded()); X509v1CertificateBuilder builder = new X509v1CertificateBuilder(subjectDN, serialNumber, validityStartDate, validityEndDate, subjectDN, subPubKeyInfo); X509CertificateHolder holder = builder.build(createSigner(caKeyPair.getPrivate())); return new JcaX509CertificateConverter().getCertificate(holder); } catch (Exception e) { throw new RuntimeException("Error creating X509v1Certificate.", e); } }
Example #2
Source Project: xipki Author: xipki File: CaClientExample.java License: Apache License 2.0 | 6 votes |
protected static MyKeypair generateDsaKeypair() throws Exception { // plen: 2048, qlen: 256 DSAParameterSpec spec = new DSAParameterSpec(P2048_Q256_P, P2048_Q256_Q, P2048_Q256_G); KeyPairGenerator kpGen = KeyPairGenerator.getInstance("DSA"); kpGen.initialize(spec); KeyPair kp = kpGen.generateKeyPair(); DSAPublicKey dsaPubKey = (DSAPublicKey) kp.getPublic(); ASN1EncodableVector vec = new ASN1EncodableVector(); vec.add(new ASN1Integer(dsaPubKey.getParams().getP())); vec.add(new ASN1Integer(dsaPubKey.getParams().getQ())); vec.add(new ASN1Integer(dsaPubKey.getParams().getG())); ASN1Sequence dssParams = new DERSequence(vec); SubjectPublicKeyInfo subjectPublicKeyInfo = new SubjectPublicKeyInfo( new AlgorithmIdentifier(X9ObjectIdentifiers.id_dsa, dssParams), new ASN1Integer(dsaPubKey.getY())); return new MyKeypair(kp.getPrivate(), subjectPublicKeyInfo); }
Example #3
Source Project: xipki Author: xipki File: CaClientExample.java License: Apache License 2.0 | 6 votes |
protected static MyKeypair generateDsaKeypair() throws Exception { // plen: 2048, qlen: 256 DSAParameterSpec spec = new DSAParameterSpec(P2048_Q256_P, P2048_Q256_Q, P2048_Q256_G); KeyPairGenerator kpGen = KeyPairGenerator.getInstance("DSA"); kpGen.initialize(spec); KeyPair kp = kpGen.generateKeyPair(); DSAPublicKey dsaPubKey = (DSAPublicKey) kp.getPublic(); ASN1EncodableVector vec = new ASN1EncodableVector(); vec.add(new ASN1Integer(dsaPubKey.getParams().getP())); vec.add(new ASN1Integer(dsaPubKey.getParams().getQ())); vec.add(new ASN1Integer(dsaPubKey.getParams().getG())); ASN1Sequence dssParams = new DERSequence(vec); SubjectPublicKeyInfo subjectPublicKeyInfo = new SubjectPublicKeyInfo( new AlgorithmIdentifier(X9ObjectIdentifiers.id_dsa, dssParams), new ASN1Integer(dsaPubKey.getY())); return new MyKeypair(kp.getPrivate(), subjectPublicKeyInfo); }
Example #4
Source Project: PacketProxy Author: DeNA File: CA.java License: Apache License 2.0 | 6 votes |
private void initKeyStoreCA(InputStream input) throws Exception { this.keyStoreCA = KeyStore.getInstance("JKS"); this.keyStoreCA.load(input, password); this.keyStoreCAPrivateKey = (PrivateKey) keyStoreCA.getKey(aliasRoot, password); /* RootのSubject(Issuer)の取り出し */ Certificate caRootCert = keyStoreCA.getCertificate(aliasRoot); caRootHolder = new X509CertificateHolder(caRootCert.getEncoded()); /* 有効期限の設定 */ Date from = new Date(); Calendar cal = Calendar.getInstance(); cal.setTime(from); cal.add(Calendar.YEAR, 1); Date to = cal.getTime(); /* Templateの設定 */ templateIssuer = caRootHolder.getSubject(); templateFrom = from; templateTo = to; templatePubKey = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()); }
Example #5
Source Project: Spark Author: igniterealtime File: IdentityController.java License: Apache License 2.0 | 6 votes |
public X509Certificate createSelfSignedCertificate(KeyPair keyPair) throws NoSuchAlgorithmException, NoSuchProviderException, CertIOException, OperatorCreationException, CertificateException { long serial = System.currentTimeMillis(); SubjectPublicKeyInfo keyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()); X500Name name = new X500Name(createX500NameString()); X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(name, BigInteger.valueOf(serial), new Date(System.currentTimeMillis() - 1000000000), new Date(System.currentTimeMillis() + 1000000000), name, keyInfo ); certBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true)); certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); certBuilder.addExtension(Extension.extendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth)); JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder("SHA256withRSA"); ContentSigner signer = csBuilder.build(keyPair.getPrivate()); X509CertificateHolder certHolder = certBuilder.build(signer); X509Certificate cert = new JcaX509CertificateConverter().getCertificate(certHolder); return cert; }
Example #6
Source Project: weixin-java-tools Author: DarLiner File: EntPayServiceImpl.java License: Apache License 2.0 | 6 votes |
private String encryptRSA(File publicKeyFile, String srcString) throws WxPayException { try { Security.addProvider(new BouncyCastleProvider()); Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding"); try (PEMParser reader = new PEMParser(new FileReader(publicKeyFile))) { final PublicKey publicKey = new JcaPEMKeyConverter().setProvider("BC") .getPublicKey((SubjectPublicKeyInfo) reader.readObject()); cipher.init(Cipher.ENCRYPT_MODE, publicKey); byte[] encrypt = cipher.doFinal(srcString.getBytes()); return Base64.encodeBase64String(encrypt); } } catch (Exception e) { throw new WxPayException("加密出错", e); } }
Example #7
Source Project: littleca Author: dushitaoyuan File: CAImpl.java License: Apache License 2.0 | 6 votes |
@Override public PKCS10CertificationRequest makeUserCertReq(PublicKey publicKey, String userDN, String signAlg) throws CertException { try { PKCS10CertificationRequestBuilder builder = new PKCS10CertificationRequestBuilder(new X500Name(userDN) ,SubjectPublicKeyInfo.getInstance(publicKey.getEncoded())); if(null==signAlg) { signAlg=DEFAULT_SIGN_ALG; } JcaContentSignerBuilder jcaBuilder = new JcaContentSignerBuilder(signAlg); jcaBuilder.setProvider(BouncyCastleProvider.PROVIDER_NAME); ContentSigner contentSigner = jcaBuilder.build(privateKey); PKCS10CertificationRequest certificationRequest = builder.build(contentSigner); return certificationRequest; } catch (Exception e) { throw new CertException("makeUserCertReq failed",e); } }
Example #8
Source Project: localization_nifi Author: wangrenlei File: OcspCertificateValidatorTest.java License: Apache License 2.0 | 6 votes |
/** * Generates a certificate with a specific public key signed by the issuer key. * * @param dn the subject DN * @param publicKey the subject public key * @param issuerDn the issuer DN * @param issuerKey the issuer private key * @return the certificate * @throws IOException if an exception occurs * @throws NoSuchAlgorithmException if an exception occurs * @throws CertificateException if an exception occurs * @throws NoSuchProviderException if an exception occurs * @throws SignatureException if an exception occurs * @throws InvalidKeyException if an exception occurs * @throws OperatorCreationException if an exception occurs */ private static X509Certificate generateIssuedCertificate(String dn, PublicKey publicKey, String issuerDn, PrivateKey issuerKey) throws IOException, NoSuchAlgorithmException, CertificateException, NoSuchProviderException, SignatureException, InvalidKeyException, OperatorCreationException { ContentSigner sigGen = new JcaContentSignerBuilder(SIGNATURE_ALGORITHM).setProvider(PROVIDER).build(issuerKey); SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()); Date startDate = new Date(YESTERDAY); Date endDate = new Date(ONE_YEAR_FROM_NOW); X509v3CertificateBuilder v3CertGen = new X509v3CertificateBuilder( new X500Name(issuerDn), BigInteger.valueOf(System.currentTimeMillis()), startDate, endDate, new X500Name(dn), subPubKeyInfo); X509CertificateHolder certificateHolder = v3CertGen.build(sigGen); return new JcaX509CertificateConverter().setProvider(PROVIDER) .getCertificate(certificateHolder); }
Example #9
Source Project: Launcher Author: GravitLauncher File: CertificateManager.java License: GNU General Public License v3.0 | 6 votes |
public X509CertificateHolder generateCertificate(String subjectName, PublicKey subjectPublicKey) throws OperatorCreationException { SubjectPublicKeyInfo subjectPubKeyInfo = SubjectPublicKeyInfo.getInstance(subjectPublicKey.getEncoded()); BigInteger serial = BigInteger.valueOf(SecurityHelper.newRandom().nextLong()); Date startDate = Date.from(Instant.now().minus(minusHours, ChronoUnit.HOURS)); Date endDate = Date.from(startDate.toInstant().plus(validDays, ChronoUnit.DAYS)); X500NameBuilder subject = new X500NameBuilder(); subject.addRDN(BCStyle.CN, subjectName); subject.addRDN(BCStyle.O, orgName); X509v3CertificateBuilder v3CertGen = new X509v3CertificateBuilder(ca.getSubject(), serial, startDate, endDate, subject.build(), subjectPubKeyInfo); AlgorithmIdentifier sigAlgId = ca.getSignatureAlgorithm(); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); ContentSigner sigGen = new BcECContentSignerBuilder(sigAlgId, digAlgId).build(caKey); return v3CertGen.build(sigGen); }
Example #10
Source Project: Launcher Author: GravitLauncher File: CertificateManager.java License: GNU General Public License v3.0 | 6 votes |
public void generateCA() throws NoSuchAlgorithmException, IOException, OperatorCreationException, InvalidAlgorithmParameterException { ECGenParameterSpec ecGenSpec = new ECGenParameterSpec("secp384k1"); KeyPairGenerator generator = KeyPairGenerator.getInstance("EC"); generator.initialize(ecGenSpec, SecurityHelper.newRandom()); KeyPair pair = generator.generateKeyPair(); LocalDateTime startDate = LocalDate.now().atStartOfDay(); X500NameBuilder subject = new X500NameBuilder(); subject.addRDN(BCStyle.CN, orgName.concat(" CA")); subject.addRDN(BCStyle.O, orgName); X509v3CertificateBuilder builder = new X509v3CertificateBuilder( subject.build(), new BigInteger("0"), Date.from(startDate.atZone(ZoneId.systemDefault()).toInstant()), Date.from(startDate.plusDays(3650).atZone(ZoneId.systemDefault()).toInstant()), new X500Name("CN=ca"), SubjectPublicKeyInfo.getInstance(pair.getPublic().getEncoded())); JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder("SHA256WITHECDSA"); ContentSigner signer = csBuilder.build(pair.getPrivate()); ca = builder.build(signer); caKey = PrivateKeyFactory.createKey(pair.getPrivate().getEncoded()); }
Example #11
Source Project: nifi Author: apache File: OcspCertificateValidatorTest.java License: Apache License 2.0 | 6 votes |
/** * Generates a certificate with a specific public key signed by the issuer key. * * @param dn the subject DN * @param publicKey the subject public key * @param issuerDn the issuer DN * @param issuerKey the issuer private key * @return the certificate * @throws IOException if an exception occurs * @throws NoSuchAlgorithmException if an exception occurs * @throws CertificateException if an exception occurs * @throws NoSuchProviderException if an exception occurs * @throws SignatureException if an exception occurs * @throws InvalidKeyException if an exception occurs * @throws OperatorCreationException if an exception occurs */ private static X509Certificate generateIssuedCertificate(String dn, PublicKey publicKey, String issuerDn, PrivateKey issuerKey) throws IOException, NoSuchAlgorithmException, CertificateException, NoSuchProviderException, SignatureException, InvalidKeyException, OperatorCreationException { ContentSigner sigGen = new JcaContentSignerBuilder(SIGNATURE_ALGORITHM).setProvider(PROVIDER).build(issuerKey); SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()); Date startDate = new Date(YESTERDAY); Date endDate = new Date(ONE_YEAR_FROM_NOW); X509v3CertificateBuilder v3CertGen = new X509v3CertificateBuilder( new X500Name(issuerDn), BigInteger.valueOf(System.currentTimeMillis()), startDate, endDate, new X500Name(dn), subPubKeyInfo); X509CertificateHolder certificateHolder = v3CertGen.build(sigGen); return new JcaX509CertificateConverter().setProvider(PROVIDER) .getCertificate(certificateHolder); }
Example #12
Source Project: guardedbox Author: s3curitybug File: SignatureVerificationService.java License: GNU Affero General Public License v3.0 | 6 votes |
/** * Verifies a signature. * * @param originalMessage The original message. * @param signedMessage The signature of the original message. * @param signingPublicKey The public key corresponding to the private key used to sign the message. * @return Boolean indicating if the signature is verified. */ public boolean verifySignature( byte[] originalMessage, byte[] signedMessage, byte[] signingPublicKey) { try { KeyFactory keyFactory = KeyFactory.getInstance(cryptographyProperties.getSignatureAlgorithm(), BouncyCastleProvider.PROVIDER_NAME); KeySpec keySpec = new X509EncodedKeySpec(new SubjectPublicKeyInfo(signatureAlgorithmId, signingPublicKey).getEncoded()); PublicKey pubKey = keyFactory.generatePublic(keySpec); Signature signature = Signature.getInstance(cryptographyProperties.getSignatureAlgorithm(), BouncyCastleProvider.PROVIDER_NAME); signature.initVerify(pubKey); signature.update(originalMessage); return signature.verify(signedMessage); } catch (NoSuchAlgorithmException | NoSuchProviderException | IOException | InvalidKeySpecException | InvalidKeyException | SignatureException e) { return false; } }
Example #13
Source Project: xipki Author: xipki File: ProxyP11Slot.java License: Apache License 2.0 | 6 votes |
private PublicKey getPublicKey(P11ObjectIdentifier objectId) throws P11UnknownEntityException, P11TokenException { ASN1Object req = new ProxyMessage.SlotIdAndObjectId(asn1SlotId, new ProxyMessage.ObjectIdentifier(objectId)); byte[] resp = module.send(P11ProxyConstants.ACTION_GET_PUBLICKEY, req); if (resp == null) { return null; } SubjectPublicKeyInfo pkInfo = SubjectPublicKeyInfo.getInstance(resp); try { return KeyUtil.generatePublicKey(pkInfo); } catch (InvalidKeySpecException ex) { throw new P11TokenException("could not generate Public Key from SubjectPublicKeyInfo:" + ex.getMessage(), ex); } }
Example #14
Source Project: chvote-1-0 Author: republique-et-canton-de-geneve File: KeyGenerator.java License: GNU Affero General Public License v3.0 | 6 votes |
private X509v3CertificateBuilder createCertificateBuilder(KeyPair keyPair) throws PropertyConfigurationException, CertIOException { X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE); nameBuilder.addRDN(BCStyle.CN, propertyConfigurationService.getConfigValue(CERT_COMMON_NAME_PROPERTY)); nameBuilder.addRDN(BCStyle.O, propertyConfigurationService.getConfigValue(CERT_ORGANISATION_PROPERTY)); nameBuilder.addRDN(BCStyle.OU, propertyConfigurationService.getConfigValue(CERT_ORGANISATIONAL_UNIT_PROPERTY)); nameBuilder.addRDN(BCStyle.C, propertyConfigurationService.getConfigValue(CERT_COUNTRY_PROPERTY)); X500Name x500Name = nameBuilder.build(); BigInteger serial = new BigInteger(CERT_SERIAL_NUMBER_BIT_SIZE, SecureRandomFactory.createPRNG()); SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()); Date startDate = new Date(); Date endDate = Date.from(startDate.toInstant().plus(propertyConfigurationService.getConfigValueAsInt(CERT_VALIDITY_DAYS_PROPERTY), ChronoUnit.DAYS)); X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(x500Name, serial, startDate, endDate, x500Name, publicKeyInfo); String certFriendlyName = propertyConfigurationService.getConfigValue(CERT_PRIVATE_FRIENDLY_NAME_PROPERTY); certificateBuilder.addExtension(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, false, new DERBMPString(certFriendlyName)); return certificateBuilder; }
Example #15
Source Project: peer-os Author: subutai-io File: PGPEncryptionUtil.java License: Apache License 2.0 | 6 votes |
public static X509Certificate getX509CertificateFromPgpKeyPair( PGPPublicKey pgpPublicKey, PGPSecretKey pgpSecretKey, String secretPwd, String issuer, String subject, Date dateOfIssue, Date dateOfExpiry, BigInteger serial ) throws PGPException, CertificateException, IOException { JcaPGPKeyConverter c = new JcaPGPKeyConverter(); PublicKey publicKey = c.getPublicKey( pgpPublicKey ); PrivateKey privateKey = c.getPrivateKey( pgpSecretKey.extractPrivateKey( new JcePBESecretKeyDecryptorBuilder().setProvider( provider ).build( secretPwd.toCharArray() ) ) ); X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder( new X500Name( issuer ), serial, dateOfIssue, dateOfExpiry, new X500Name( subject ), SubjectPublicKeyInfo.getInstance( publicKey.getEncoded() ) ); byte[] certBytes = certBuilder.build( new JCESigner( privateKey, "SHA256withRSA" ) ).getEncoded(); CertificateFactory certificateFactory = CertificateFactory.getInstance( "X.509" ); return ( X509Certificate ) certificateFactory.generateCertificate( new ByteArrayInputStream( certBytes ) ); }
Example #16
Source Project: xipki Author: xipki File: X509Cert.java License: Apache License 2.0 | 6 votes |
public SubjectPublicKeyInfo getSubjectPublicKeyInfo() { if (subjectPublicKeyInfo == null) { synchronized (sync) { if (bcInstance != null) { subjectPublicKeyInfo = bcInstance.getSubjectPublicKeyInfo(); } else { try { subjectPublicKeyInfo = KeyUtil.createSubjectPublicKeyInfo(jceInstance.getPublicKey()); } catch (InvalidKeyException ex) { throw new IllegalStateException("error creating SubjectPublicKeyInfo from PublicKey", ex); } } } } return subjectPublicKeyInfo; }
Example #17
Source Project: xipki Author: xipki File: CaClientExample.java License: Apache License 2.0 | 6 votes |
protected static MyKeypair generateEcKeypair() throws GeneralSecurityException { KeyPairGenerator kpGen = KeyPairGenerator.getInstance("EC"); ECGenParameterSpec spec = new ECGenParameterSpec("secp256r1"); kpGen.initialize(spec); KeyPair kp = kpGen.generateKeyPair(); ECPublicKey pub = (ECPublicKey) kp.getPublic(); byte[] keyData = new byte[65]; keyData[0] = 4; copyArray(pub.getW().getAffineX().toByteArray(), keyData, 1, 32); copyArray(pub.getW().getAffineY().toByteArray(), keyData, 33, 32); AlgorithmIdentifier algId = new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, SECObjectIdentifiers.secp256r1); SubjectPublicKeyInfo subjectPublicKeyInfo = new SubjectPublicKeyInfo(algId, keyData); return new MyKeypair(kp.getPrivate(), subjectPublicKeyInfo); }
Example #18
Source Project: vertx-tcp-eventbus-bridge Author: vert-x3 File: SSLKeyPairCerts.java License: Apache License 2.0 | 6 votes |
private X509Certificate generateSelfSignedCert(String certSub, KeyPair keyPair) throws Exception { final X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder( new org.bouncycastle.asn1.x500.X500Name(certSub), BigInteger.ONE, new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30), new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30)), new X500Name(certSub), SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()) ); final GeneralNames subjectAltNames = new GeneralNames(new GeneralName(GeneralName.iPAddress, "127.0.0.1")); certificateBuilder.addExtension(org.bouncycastle.asn1.x509.Extension.subjectAlternativeName, false, subjectAltNames); final AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1WithRSAEncryption"); final AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); final BcContentSignerBuilder signerBuilder = new BcRSAContentSignerBuilder(sigAlgId, digAlgId); final AsymmetricKeyParameter keyp = PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded()); final ContentSigner signer = signerBuilder.build(keyp); final X509CertificateHolder x509CertificateHolder = certificateBuilder.build(signer); final X509Certificate certificate = new JcaX509CertificateConverter().getCertificate(x509CertificateHolder); certificate.checkValidity(new Date()); certificate.verify(keyPair.getPublic()); return certificate; }
Example #19
Source Project: xipki Author: xipki File: SelfSignedCertBuilder.java License: Apache License 2.0 | 6 votes |
private static void addExtensions(X509v3CertificateBuilder certBuilder, IdentifiedCertprofile profile, X500Name requestedSubject, X500Name grantedSubject, Extensions extensions, SubjectPublicKeyInfo requestedPublicKeyInfo, PublicCaInfo publicCaInfo, Date notBefore, Date notAfter) throws CertprofileException, IOException, BadCertTemplateException { ExtensionValues extensionTuples = profile.getExtensions(requestedSubject, grantedSubject, extensions, requestedPublicKeyInfo, publicCaInfo, null, notBefore, notAfter); if (extensionTuples == null) { return; } for (ASN1ObjectIdentifier extType : extensionTuples.getExtensionTypes()) { ExtensionValue extValue = extensionTuples.getExtensionValue(extType); certBuilder.addExtension(extType, extValue.isCritical(), extValue.getValue()); } }
Example #20
Source Project: fido2 Author: StrongKey File: cryptoCommon.java License: GNU Lesser General Public License v2.1 | 5 votes |
/** * Method to verify attestation certificate * * @param attestationCertificate - the attestation cert to be verified * @return - boolean, based on the result of verification */ public static boolean verifyU2FAttestationCertificate(X509Certificate attestationCertificate) { PublicKey attcertPublicKey = attestationCertificate.getPublicKey(); byte[] attPublicKey = attcertPublicKey.getEncoded(); SubjectPublicKeyInfo spki = SubjectPublicKeyInfo.getInstance(ASN1Sequence.getInstance(attPublicKey)); spki.getAlgorithm(); // get algorithm from the AlgorithmIdentifier refer to RFC 5480 AlgorithmIdentifier sigAlgId = spki.getAlgorithm(); ASN1ObjectIdentifier asoi = sigAlgId.getAlgorithm(); if (!(asoi.getId().equals("1.2.840.10045.2.1"))) { //not an EC Public Key logp(Level.SEVERE, classname, "verifyAttestationCertificate", "FIDO-ERR-5008", "Only Elliptic-Curve (EC) keys are allowed, the public key in this certificate not an EC public key"); return false; } // Get parameters from AlgorithmIdentifier, parameters field is optional RFC 5480, ASN1Encodable asne = sigAlgId.getParameters(); if (asne == null) { logp(Level.WARNING, classname, "verifyAttestationCertificate", "FIDO-WARN-5001", ""); } else { if (!(asne.toString().equals("1.2.840.10045.3.1.7"))) { //key not generated using curve secp256r1 logp(Level.SEVERE, classname, "verifyAttestationCertificate", "FIDO-ERR-5009", ""); return false; } } logp(Level.FINE, classname, "verifyAttestationCertificate", "FIDO-MSG-5025", ""); return true; }
Example #21
Source Project: xipki Author: xipki File: CaClientExample.java License: Apache License 2.0 | 5 votes |
protected static MyKeypair generateRsaKeypair() throws Exception { KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA"); kpGen.initialize(2048); KeyPair kp = kpGen.generateKeyPair(); RSAPublicKey pubKey = (RSAPublicKey) kp.getPublic(); SubjectPublicKeyInfo subjectPublicKeyInfo = new SubjectPublicKeyInfo( new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE), new org.bouncycastle.asn1.pkcs.RSAPublicKey(pubKey.getModulus(), pubKey.getPublicExponent())); return new MyKeypair(kp.getPrivate(), subjectPublicKeyInfo); }
Example #22
Source Project: xipki Author: xipki File: CtLogVerifyTest.java License: Apache License 2.0 | 5 votes |
@Test public void testVerify() throws Exception { Security.addProvider(new BouncyCastleProvider()); byte[] keyBytes = read(pubkeyFile); SubjectPublicKeyInfo spki = SubjectPublicKeyInfo.getInstance(X509Util.toDerEncoded(keyBytes)); byte[] keyId = HashAlgo.SHA256.hash(spki.getEncoded()); System.out.println("keyId: " + Hex.encode(keyId)); PublicKey key = KeyUtil.generatePublicKey(spki); X509Cert cert = X509Util.parseCert(read(certFile)); X509Cert caCert = X509Util.parseCert(read(caCertFile)); // CHECKSTYLE:SKIP byte[] issuerKeyHash = HashAlgo.SHA256.hash(caCert.getSubjectPublicKeyInfo().getEncoded()); // CHECKSTYLE:SKIP byte[] preCertTbsCert = CtLog.getPreCertTbsCert( cert.toBcCert().toASN1Structure().getTBSCertificate()); byte[] extnValue = cert.getExtensionCoreValue(ObjectIdentifiers.Extn.id_SCTs); byte[] encodedScts = ASN1OctetString.getInstance(extnValue).getOctets(); SignedCertificateTimestampList list = SignedCertificateTimestampList.getInstance(encodedScts); SerializedSCT sctList = list.getSctList(); int size = sctList.size(); Assert.assertEquals("SCT size", 2, size); SignedCertificateTimestamp sct = sctList.get(1); byte[] logId = sct.getLogId(); Assert.assertEquals("logId", Hex.encodeUpper(keyId), Hex.encodeUpper(logId)); Signature sig = Signature.getInstance("SHA256withECDSA"); sig.initVerify(key); CtLog.update(sig, (byte) sct.getVersion(), sct.getTimestamp(), sct.getExtensions(), issuerKeyHash, preCertTbsCert); boolean sigValid = sig.verify(sct.getDigitallySigned().getSignature()); Assert.assertEquals("signature valid", true, sigValid); }
Example #23
Source Project: javasdk Author: hyperchain File: CertUtil.java License: GNU Lesser General Public License v3.0 | 5 votes |
/** * read pem and convert to address. * @param s pem file context * @return address * @throws Exception - */ public static String pemToAddr(String s) throws Exception { PemReader pemReader = new PemReader(new StringReader(s)); PemObject pemObject = pemReader.readPemObject(); X509CertificateHolder cert = new X509CertificateHolder(pemObject.getContent()); SubjectPublicKeyInfo pkInfo = cert.getSubjectPublicKeyInfo(); DERBitString pk = pkInfo.getPublicKeyData(); byte[] pk64 = ByteUtils.subArray(pk.getBytes(),1); return ByteUtils.toHexString(HashUtil.sha3omit12(pk64)); }
Example #24
Source Project: xipki Author: xipki File: CaClientExample.java License: Apache License 2.0 | 5 votes |
protected static MyKeypair generateRsaKeypair() throws Exception { KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA"); kpGen.initialize(2048); KeyPair kp = kpGen.generateKeyPair(); RSAPublicKey pubKey = (RSAPublicKey) kp.getPublic(); SubjectPublicKeyInfo subjectPublicKeyInfo = new SubjectPublicKeyInfo( new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE), new org.bouncycastle.asn1.pkcs.RSAPublicKey(pubKey.getModulus(), pubKey.getPublicExponent())); return new MyKeypair(kp.getPrivate(), subjectPublicKeyInfo); }
Example #25
Source Project: hedera-sdk-java Author: hashgraph File: PublicKey.java License: Apache License 2.0 | 5 votes |
public static PublicKey fromString(String keyString) { SubjectPublicKeyInfo pubKeyInfo; try { byte[] keyBytes = Hex.decode(keyString); // it could be a hex-encoded raw public key or a DER-encoded public key if (keyBytes.length == Ed25519.PUBLIC_KEY_SIZE) { return Ed25519PublicKey.fromBytes(keyBytes); } pubKeyInfo = SubjectPublicKeyInfo.getInstance(keyBytes); } catch (Exception e) { throw new IllegalArgumentException("Failed to parse public key", e); } ASN1ObjectIdentifier algId = pubKeyInfo.getAlgorithm() .getAlgorithm(); if (algId.equals(EdECObjectIdentifiers.id_Ed25519)) { return Ed25519PublicKey.fromBytes( pubKeyInfo.getPublicKeyData() .getBytes()); } else { throw new IllegalArgumentException("Unsupported public key type: " + algId.toString()); } }
Example #26
Source Project: freehealth-connector Author: taktik File: NewCertificateContract.java License: GNU Affero General Public License v3.0 | 5 votes |
private int getKeySize(SubjectPublicKeyInfo subjectPKInfo) { try { X509EncodedKeySpec xspec = new X509EncodedKeySpec((new DERBitString(subjectPKInfo.getEncoded())).getBytes()); AlgorithmIdentifier keyAlg = subjectPKInfo.getAlgorithm(); PublicKey publicKey = KeyFactory.getInstance(keyAlg.getAlgorithm().getId()).generatePublic(xspec); String algorithm = publicKey.getAlgorithm(); KeyFactory keyFact = KeyFactory.getInstance(algorithm); RSAPublicKeySpec keySpec = (RSAPublicKeySpec)keyFact.getKeySpec(publicKey, RSAPublicKeySpec.class); BigInteger modulus = keySpec.getModulus(); return modulus.toString(2).length(); } catch (Exception var9) { throw new IllegalArgumentException(var9); } }
Example #27
Source Project: xipki Author: xipki File: P12KeyGenerator.java License: Apache License 2.0 | 5 votes |
private KeyPairWithSubjectPublicKeyInfo genRSAKeypair(int keysize, BigInteger publicExponent, SecureRandom random) throws Exception { KeyPair kp = KeyUtil.generateRSAKeypair(keysize, publicExponent, random); java.security.interfaces.RSAPublicKey rsaPubKey = (java.security.interfaces.RSAPublicKey) kp.getPublic(); SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo( new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE), new RSAPublicKey(rsaPubKey.getModulus(), rsaPubKey.getPublicExponent())); return new KeyPairWithSubjectPublicKeyInfo(kp, spki); }
Example #28
Source Project: freehealth-connector Author: taktik File: NewCertificateContract.java License: GNU Affero General Public License v3.0 | 5 votes |
private int getKeySize(SubjectPublicKeyInfo subjectPKInfo) { try { X509EncodedKeySpec xspec = new X509EncodedKeySpec((new DERBitString(subjectPKInfo.getEncoded())).getBytes()); AlgorithmIdentifier keyAlg = subjectPKInfo.getAlgorithm(); PublicKey publicKey = KeyFactory.getInstance(keyAlg.getAlgorithm().getId()).generatePublic(xspec); String algorithm = publicKey.getAlgorithm(); KeyFactory keyFact = KeyFactory.getInstance(algorithm); RSAPublicKeySpec keySpec = (RSAPublicKeySpec)keyFact.getKeySpec(publicKey, RSAPublicKeySpec.class); BigInteger modulus = keySpec.getModulus(); return modulus.toString(2).length(); } catch (Exception var9) { throw new IllegalArgumentException(var9); } }
Example #29
Source Project: gmhelper Author: ZZMarquis File: SM2PublicKey.java License: Apache License 2.0 | 5 votes |
@Override public byte[] getEncoded() { ASN1OctetString p = ASN1OctetString.getInstance( new X9ECPoint(getQ(), withCompression).toASN1Primitive()); // stored curve is null if ImplicitlyCa SubjectPublicKeyInfo info = new SubjectPublicKeyInfo( new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, ID_SM2_PUBKEY_PARAM), p.getOctets()); return KeyUtil.getEncodedSubjectPublicKeyInfo(info); }
Example #30
Source Project: gmhelper Author: ZZMarquis File: SM2PrivateKey.java License: Apache License 2.0 | 5 votes |
private DERBitString getSM2PublicKeyDetails(SM2PublicKey pub) { try { SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(ASN1Primitive.fromByteArray(pub.getEncoded())); return info.getPublicKeyData(); } catch (IOException e) { // should never happen return null; } }