org.bouncycastle.asn1.x509.SubjectPublicKeyInfo Java Examples

The following examples show how to use org.bouncycastle.asn1.x509.SubjectPublicKeyInfo. 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 File: SSLKeyPairCerts.java    From vertx-tcp-eventbus-bridge with Apache License 2.0 6 votes vote down vote up
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 #2
Source File: CA.java    From PacketProxy with Apache License 2.0 6 votes vote down vote up
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 #3
Source File: SelfSignedCertBuilder.java    From xipki with Apache License 2.0 6 votes vote down vote up
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 #4
Source File: IdentityController.java    From Spark with Apache License 2.0 6 votes vote down vote up
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 #5
Source File: CaClientExample.java    From xipki with Apache License 2.0 6 votes vote down vote up
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 #6
Source File: CaClientExample.java    From xipki with Apache License 2.0 6 votes vote down vote up
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 #7
Source File: CertificateUtils.java    From keycloak with Apache License 2.0 6 votes vote down vote up
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 #8
Source File: EntPayServiceImpl.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
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 #9
Source File: CaClientExample.java    From xipki with Apache License 2.0 6 votes vote down vote up
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 #10
Source File: X509Cert.java    From xipki with Apache License 2.0 6 votes vote down vote up
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 #11
Source File: PGPEncryptionUtil.java    From peer-os with Apache License 2.0 6 votes vote down vote up
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 #12
Source File: CAImpl.java    From littleca with Apache License 2.0 6 votes vote down vote up
@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 #13
Source File: KeyGenerator.java    From chvote-1-0 with GNU Affero General Public License v3.0 6 votes vote down vote up
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 #14
Source File: OcspCertificateValidatorTest.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #15
Source File: CertificateManager.java    From Launcher with GNU General Public License v3.0 6 votes vote down vote up
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 #16
Source File: CertificateManager.java    From Launcher with GNU General Public License v3.0 6 votes vote down vote up
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 #17
Source File: ProxyP11Slot.java    From xipki with Apache License 2.0 6 votes vote down vote up
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 #18
Source File: SignatureVerificationService.java    From guardedbox with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 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 #19
Source File: OcspCertificateValidatorTest.java    From nifi with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #20
Source File: CertificateGeneratorTest.java    From credhub with Apache License 2.0 5 votes vote down vote up
private X509CertificateHolder makeCert(final KeyPair certKeyPair,
                                       final PrivateKey caPrivateKey,
                                       final X500Name caDn,
                                       final X500Name subjectDn,
                                       final boolean isCa) throws OperatorCreationException, NoSuchAlgorithmException, CertIOException {
  final SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(certKeyPair.getPublic()
    .getEncoded());
  final ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256withRSA")
    .setProvider(BouncyCastleFipsProvider.PROVIDER_NAME)
    .build(caPrivateKey);

  final CurrentTimeProvider currentTimeProvider = new CurrentTimeProvider();

  final Instant now = Instant.from(currentTimeProvider.getInstant());

  final X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder(
    caDn,
    BigInteger.TEN,
    Date.from(now),
    Date.from(now.plus(Duration.ofDays(365))),
    subjectDn,
    publicKeyInfo
  );
  x509v3CertificateBuilder
    .addExtension(Extension.basicConstraints, true, new BasicConstraints(isCa));
  return x509v3CertificateBuilder.build(contentSigner);
}
 
Example #21
Source File: DeviceCertificateManager.java    From enmasse with Apache License 2.0 5 votes vote down vote up
private static AuthorityKeyIdentifier createAuthorityKeyId(final PublicKey publicKey)
        throws OperatorCreationException {

    final SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());
    final DigestCalculator digCalc = new BcDigestCalculatorProvider()
            .get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1));

    return new X509ExtensionUtils(digCalc)
            .createAuthorityKeyIdentifier(publicKeyInfo);

}
 
Example #22
Source File: KeyCodecTest.java    From UAF with Apache License 2.0 5 votes vote down vote up
@Test
public void pss() throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException, DataLengthException, CryptoException, InvalidKeyException, SignatureException, InvalidKeySpecException, IOException{
	KeyPair keyPair = KeyCodec.getRSAKeyPair();
	KeyPair keyPair2 = KeyCodec.getRSAKeyPair();
	
	PrivateKey privKey = keyPair.getPrivate();
	byte[] encodedPrivKey = privKey.getEncoded();
	logger.info("priv=" + Base64.encodeBase64URLSafeString(encodedPrivKey));

	PublicKey pubKey = keyPair.getPublic();
	byte[] encodedPubKey = pubKey.getEncoded();
	SubjectPublicKeyInfo spkInfo = SubjectPublicKeyInfo.getInstance(encodedPubKey);
	ASN1Primitive primitive = spkInfo.parsePublicKey();
	
	PublicKey publicKey = KeyCodec.getRSAPublicKey(primitive.getEncoded());
	logger.info("pub=" + Base64.encodeBase64URLSafeString(encodedPubKey));
	logger.info("pub format=" + pubKey.getFormat());
	logger.info("pub alg=" + pubKey.getAlgorithm());
	
	byte[] slt = Hex.decode("dee959c7e06411361420ff80185ed57f3e6776af"); //a random salt
	
	byte[] signed = RSA.signPSS(privKey, slt);
	assertTrue(signed.length>0);
	RSA rsa = new RSA();
	Assert.assertTrue(rsa.verifyPSS(publicKey, slt, signed));
	byte[] slt2 = Hex.decode("dee959c7e06411361420ff80185ed57f3e6776aa"); //a random salt  
	
	byte[] signed2 = RSA.signPSS(keyPair2.getPrivate(), slt2);
	Assert.assertFalse(rsa.verifyPSS(publicKey, slt2, signed2));
	Assert.assertFalse(rsa.verifyPSS(keyPair2.getPublic(), slt, signed));
}
 
Example #23
Source File: CaEnrollBenchKeyEntry.java    From xipki with Apache License 2.0 5 votes vote down vote up
public RSAKeyEntry(int keysize) throws Exception {
  if (keysize % 1024 != 0) {
    throw new IllegalArgumentException("invalid RSA keysize " + keysize);
  }

  AlgorithmIdentifier keyAlgId = new AlgorithmIdentifier(
      PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE);

  String modulusStr;
  if (keysize == 1024 || keysize == 2048 || keysize == 3072 || keysize == 4096) {
    if (keysize == 1024) {
      modulusStr = N_1024;
    } else if (keysize == 2048) {
      modulusStr = N_2048;
    } else if (keysize == 3072) {
      modulusStr = N_3072;
    } else { // if (keysize == 4096) {
      modulusStr = N_4096;
    }
    BigInteger modulus = base64ToInt(modulusStr);
    this.spki = new SubjectPublicKeyInfo(keyAlgId,
        new org.bouncycastle.asn1.pkcs.RSAPublicKey(modulus, PUBLIC_EXPONENT));
  } else {
    KeyPairGenerator kp = KeyPairGenerator.getInstance("RSA");
    kp.initialize(keysize);
    RSAPublicKey publicKey = (RSAPublicKey) kp.generateKeyPair().getPublic();
    this.spki = new SubjectPublicKeyInfo(keyAlgId,
        new org.bouncycastle.asn1.pkcs.RSAPublicKey(
            publicKey.getModulus(), publicKey.getPublicExponent()));
  }
}
 
Example #24
Source File: CertificateUtils.java    From nifi-registry with Apache License 2.0 5 votes vote down vote up
/**
 * 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
 */
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);
    }
}
 
Example #25
Source File: SAML2SPKeystoreTest.java    From syncope with Apache License 2.0 5 votes vote down vote up
private static Certificate createSelfSignedCert(final KeyPair keyPair) throws Exception {
    final X500Name dn = new X500Name("cn=Unknown");
    final V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator();

    certGen.setSerialNumber(new ASN1Integer(BigInteger.valueOf(1)));
    certGen.setIssuer(dn);
    certGen.setSubject(dn);
    certGen.setStartDate(new Time(new Date(System.currentTimeMillis() - 1000L)));

    final Date expiration = new Date(System.currentTimeMillis() + 100000);
    certGen.setEndDate(new Time(expiration));

    final AlgorithmIdentifier sigAlgID = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption, DERNull.INSTANCE);
    certGen.setSignature(sigAlgID);
    certGen.setSubjectPublicKeyInfo(SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()));

    final Signature sig = Signature.getInstance("SHA1WithRSA");
    sig.initSign(keyPair.getPrivate());
    sig.update(certGen.generateTBSCertificate().getEncoded(ASN1Encoding.DER));

    final TBSCertificate tbsCert = certGen.generateTBSCertificate();
    final ASN1EncodableVector v = new ASN1EncodableVector();

    v.add(tbsCert);
    v.add(sigAlgID);
    v.add(new DERBitString(sig.sign()));

    final Certificate cert = CertificateFactory.getInstance("X.509")
        .generateCertificate(new ByteArrayInputStream(new DERSequence(v).getEncoded(ASN1Encoding.DER)));
    cert.verify(keyPair.getPublic());
    return cert;
}
 
Example #26
Source File: CaEmulator.java    From xipki with Apache License 2.0 5 votes vote down vote up
private boolean verifyPopo(CertificationRequest csr) {
  Args.notNull(csr, "csr");
  try {
    PKCS10CertificationRequest p10Req = new PKCS10CertificationRequest(csr);
    SubjectPublicKeyInfo pkInfo = p10Req.getSubjectPublicKeyInfo();
    PublicKey pk = generatePublicKey(pkInfo);

    ContentVerifierProvider cvp = getContentVerifierProvider(pk);
    return p10Req.isSignatureValid(cvp);
  } catch (InvalidKeyException | PKCSException | InvalidKeySpecException ex) {
    LOG.error("could not validate POPO of CSR", ex);
    return false;
  }
}
 
Example #27
Source File: KeyUtil.java    From curiostack with MIT License 5 votes vote down vote up
public static PublicKey loadPublicKey(byte[] encodedKey) {
  try (PEMParser parser = newParser(encodedKey)) {
    Object obj;
    while ((obj = parser.readObject()) != null) {
      if (obj instanceof SubjectPublicKeyInfo) {
        return newConverter().getPublicKey((SubjectPublicKeyInfo) obj);
      }
    }
    throw new IllegalStateException("Could not find public key.");
  } catch (IOException e) {
    throw new UncheckedIOException("Could not load public key.", e);
  }
}
 
Example #28
Source File: ApkUtils.java    From NBANDROID-V2 with Apache License 2.0 5 votes vote down vote up
private static Pair<PrivateKey, X509Certificate> generateKeyAndCertificate(String asymmetric, String sign, int validityYears, String dn) throws NoSuchAlgorithmException, OperatorCreationException, CertificateException {
    Preconditions.checkArgument(validityYears > 0, "validityYears <= 0");
    KeyPair keyPair = KeyPairGenerator.getInstance(asymmetric).generateKeyPair();
    Date notBefore = new Date(System.currentTimeMillis());
    Date notAfter = new Date(System.currentTimeMillis() + validityYears * 31536000000l);
    X500Name issuer = new X500Name(new X500Principal(dn).getName());
    SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
    X509v1CertificateBuilder builder = new X509v1CertificateBuilder(issuer, BigInteger.ONE, notBefore, notAfter, issuer, publicKeyInfo);
    ContentSigner signer = new JcaContentSignerBuilder(sign).setProvider(new BouncyCastleProvider()).build(keyPair.getPrivate());
    X509CertificateHolder holder = builder.build(signer);
    JcaX509CertificateConverter converter = new JcaX509CertificateConverter().setProvider(new BouncyCastleProvider());
    X509Certificate certificate = converter.getCertificate(holder);
    return Pair.of(keyPair.getPrivate(), certificate);
}
 
Example #29
Source File: cryptoCommon.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * 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 #30
Source File: CreateCA.java    From signer with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) throws IOException, OperatorCreationException, NoSuchAlgorithmException {

		// ---------------------- CA Creation ----------------------
		// System.out.println("Generating Keys");
		KeyPairGenerator rsa = KeyPairGenerator.getInstance("RSA");
		rsa.initialize(1024);
		KeyPair kp = rsa.generateKeyPair();

		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.YEAR, 100);

		// System.out.println("Getting data");
		byte[] pk = kp.getPublic().getEncoded();
		SubjectPublicKeyInfo bcPk = SubjectPublicKeyInfo.getInstance(pk);

		// System.out.println("Creating cert");
		X509v1CertificateBuilder certGen = new X509v1CertificateBuilder(new X500Name("CN=CA Cert"), BigInteger.ONE,
				new Date(), cal.getTime(), new X500Name("CN=CA Cert"), bcPk);

		X509CertificateHolder certHolder = certGen
				.build(new JcaContentSignerBuilder("SHA1withRSA").build(kp.getPrivate()));

		StringBuffer s = new StringBuffer();

		s.append(X509Factory.BEGIN_CERT + "\n");
		s.append(Base64Utils.base64Encode(certHolder.getEncoded()) + "\n");
		s.append(X509Factory.END_CERT);

		saveFile(s.toString().getBytes());

		// ---------------------- ISSUER Creation ----------------------

	}