Java Code Examples for org.bouncycastle.asn1.x509.AuthorityKeyIdentifier

The following examples show how to use org.bouncycastle.asn1.x509.AuthorityKeyIdentifier. 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
private void prepopulateWithValue(byte[] value) throws IOException {
	AuthorityKeyIdentifier authorityKeyIdentifier = AuthorityKeyIdentifier.getInstance(value);

	if (authorityKeyIdentifier.getKeyIdentifier() != null) {
		jkiKeyIdentifier.setKeyIdentifier(authorityKeyIdentifier.getKeyIdentifier());
	}

	GeneralNames authorityCertIssuer = authorityKeyIdentifier.getAuthorityCertIssuer();

	if (authorityCertIssuer != null) {
		jgnAuthorityCertIssuer.setGeneralNames(authorityCertIssuer);
	}

	BigInteger authorityCertSerialNumber = authorityKeyIdentifier.getAuthorityCertSerialNumber();

	if (authorityCertSerialNumber != null) {
		jtfAuthorityCertSerialNumber.setText("" + authorityCertSerialNumber.longValue());
		jtfAuthorityCertSerialNumber.setCaretPosition(0);
	}
}
 
Example 2
static AuthorityKeyIdentifier createAuthorityKeyId(
    PublicKey pub) 
    throws IOException
{
    SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(pub.getEncoded());

    return new AuthorityKeyIdentifier(info);
}
 
Example 3
Source Project: SecuritySample   Source File: KeyIdentifierImpl.java    License: Apache License 2.0 5 votes vote down vote up
public KeyIdentifierImpl(X509Certificate cert) throws CertificateException, IOException {
    byte[] extVal = cert.getExtensionValue(Extension.authorityKeyIdentifier.getId());
    if (extVal == null) {
        lock = true;
        return;
    }
    AuthorityKeyIdentifier aki = AuthorityKeyIdentifier.getInstance(X509ExtensionUtil.fromExtensionValue(extVal));
    keyIdentifier = aki.getKeyIdentifier();
}
 
Example 4
Source Project: fabric-sdk-java   Source File: HFCAX509Certificate.java    License: Apache License 2.0 5 votes vote down vote up
private AuthorityKeyIdentifier getAKI() throws HFCACertificateException {
    if (x509Cert == null) {
        throw new HFCACertificateException("Certificate is null");
    }
    byte[] fullExtValue = x509Cert.getExtensionValue(Extension.authorityKeyIdentifier.getId());
    byte[] extValue = ASN1OctetString.getInstance(fullExtValue).getOctets();
    return AuthorityKeyIdentifier.getInstance(extValue);
}
 
Example 5
Source Project: enmasse   Source File: DeviceCertificateManager.java    License: 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 6
private String getCertificateAKI(String alias, KeyStore keyStore) throws CryptoException, KeyStoreException {
	X509Certificate x509Cert = getCertificate(alias, keyStore);
	try {
		byte[] akiValue = x509Cert.getExtensionValue(Extension.authorityKeyIdentifier.getId());
		byte[] octets = DEROctetString.getInstance(akiValue).getOctets();
		byte[] akiBytes = AuthorityKeyIdentifier.getInstance(octets).getKeyIdentifier();
		return HexUtil.getHexString(akiBytes);
	} catch (Exception e) {
		return "-";
	}
}
 
Example 7
Source Project: dss   Source File: DSSASN1Utils.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * This method returns authority key identifier as binaries from the certificate
 * extension (SHA-1 of the public key of the issuer certificate).
 *
 * @param certificateToken
 *                         the {@code CertificateToken}
 * @return authority key identifier bytes from the given certificate (can be
 *         null if the certificate is self signed)
 */
public static byte[] getAuthorityKeyIdentifier(CertificateToken certificateToken) {
	byte[] extensionValue = certificateToken.getCertificate().getExtensionValue(Extension.authorityKeyIdentifier.getId());
	if (Utils.isArrayNotEmpty(extensionValue)) {
		try {
			ASN1Primitive extension = JcaX509ExtensionUtils.parseExtensionValue(extensionValue);
			AuthorityKeyIdentifier aki = AuthorityKeyIdentifier.getInstance(extension);
			return aki.getKeyIdentifier();
		} catch (IOException e) {
			throw new DSSException("Unable to parse the authorityKeyIdentifier extension", e);
		}
	}
	return null;
}
 
Example 8
Source Project: swift-k   Source File: AutoCA.java    License: Apache License 2.0 5 votes vote down vote up
private Map<DERObjectIdentifier, DEREncodable> createExtensions(PublicKey caPub, PublicKey userPub) throws IOException {
    Map<DERObjectIdentifier, DEREncodable> ext = new HashMap<DERObjectIdentifier, DEREncodable>();
    
    // not a CA
    ext.put(X509Extensions.BasicConstraints, new BasicConstraints(false));
    // obvious
    ext.put(X509Extensions.KeyUsage, new KeyUsage(KeyUsage.dataEncipherment | KeyUsage.digitalSignature));
    ext.put(X509Extensions.SubjectKeyIdentifier, getSubjectKeyInfo(userPub));
    ext.put(X509Extensions.AuthorityKeyIdentifier, getAuthorityKeyIdentifier(caPub));
    
    return ext;
}
 
Example 9
Source Project: xipki   Source File: X509Cert.java    License: Apache License 2.0 5 votes vote down vote up
public byte[] getAuthorityKeyId() {
  if (authorityKeyId == null) {
    synchronized (sync) {
      byte[] extnValue = getCoreExtValue(Extension.authorityKeyIdentifier);
      if (extnValue != null) {
        authorityKeyId = AuthorityKeyIdentifier.getInstance(extnValue).getKeyIdentifier();
      }
    }
  }

  return authorityKeyId;
}
 
Example 10
Source Project: xipki   Source File: CmpCaClient.java    License: Apache License 2.0 5 votes vote down vote up
public boolean revokeCert(BigInteger serialNumber, CRLReason reason) throws Exception {
  ProtectedPKIMessageBuilder builder = new ProtectedPKIMessageBuilder(
      PKIHeader.CMP_2000, requestorSubject, responderSubject);
  builder.setMessageTime(new Date());
  builder.setTransactionID(randomTransactionId());
  builder.setSenderNonce(randomSenderNonce());

  CertTemplateBuilder certTempBuilder = new CertTemplateBuilder();
  certTempBuilder.setIssuer(caSubject);
  certTempBuilder.setSerialNumber(new ASN1Integer(serialNumber));

  AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(caSubjectKeyIdentifier);
  byte[] encodedAki = aki.getEncoded();

  Extension extAki = new Extension(Extension.authorityKeyIdentifier, false, encodedAki);
  Extensions certTempExts = new Extensions(extAki);
  certTempBuilder.setExtensions(certTempExts);

  ASN1Enumerated asn1Reason = new ASN1Enumerated(reason.getValue().intValue());
  Extensions exts = new Extensions(
      new Extension(Extension.reasonCode, true, new DEROctetString(asn1Reason.getEncoded())));
  RevDetails revDetails = new RevDetails(certTempBuilder.build(), exts);

  RevReqContent content = new RevReqContent(revDetails);
  builder.setBody(new PKIBody(PKIBody.TYPE_REVOCATION_REQ, content));
  ProtectedPKIMessage request = build(builder);

  PKIMessage response = transmit(request, null);
  return parseRevocationResult(response, serialNumber);
}
 
Example 11
Source Project: xipki   Source File: CmpAgent.java    License: Apache License 2.0 5 votes vote down vote up
private static Extensions getCertTempExtensions(byte[] authorityKeyIdentifier)
    throws CmpClientException {
  AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(authorityKeyIdentifier);
  byte[] encodedAki;
  try {
    encodedAki = aki.getEncoded();
  } catch (IOException ex) {
    throw new CmpClientException("could not encoded AuthorityKeyIdentifier", ex);
  }
  Extension extAki = new Extension(Extension.authorityKeyIdentifier, false, encodedAki);
  Extensions certTempExts = new Extensions(extAki);
  return certTempExts;
}
 
Example 12
Source Project: portecle   Source File: X509Ext.java    License: GNU General Public License v2.0 4 votes vote down vote up
/**
 * Get Authority Key Identifier (2.5.29.35) extension value as a string.
 *
 * <pre>
 * AuthorityKeyIdentifier ::= SEQUENCE {
 *     keyIdentifier             [0] KeyIdentifier           OPTIONAL,
 *     authorityCertIssuer       [1] Names                   OPTIONAL,
 *     authorityCertSerialNumber [2] CertificateSerialNumber OPTIONAL }
 * KeyIdentifier ::= OCTET STRING
 * GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
 * CertificateSerialNumber  ::=  INTEGER
 * </pre>
 *
 * @param bValue The octet string value
 * @return Extension value as a string
 * @throws IOException If an I/O problem occurs
 */
private String getAuthorityKeyIdentifierStringValue(byte[] bValue)
    throws IOException
{
	AuthorityKeyIdentifier aki = AuthorityKeyIdentifier.getInstance(bValue);

	StringBuilder strBuff = new StringBuilder();

	byte[] keyIdentifier = aki.getKeyIdentifier();
	if (keyIdentifier != null)
	{
		strBuff.append(RB.getString("KeyIdentifier"));
		strBuff.append(": ");
		strBuff.append(convertToHexString(keyIdentifier));
		strBuff.append("<br>");
	}

	GeneralNames authorityCertIssuer;
	if ((authorityCertIssuer = aki.getAuthorityCertIssuer()) != null)
	{
		if (strBuff.length() != 0)
		{
			strBuff.append("<br>");
		}
		strBuff.append("<ul><li>");
		strBuff.append(RB.getString("CertificateIssuer"));
		strBuff.append(": ");
		strBuff.append(getGeneralNamesString(authorityCertIssuer, LinkClass.BROWSER));
		strBuff.append("</li></ul>");
	}

	BigInteger serialNo;
	if ((serialNo = aki.getAuthorityCertSerialNumber()) != null)
	{
		if (strBuff.length() != 0)
		{
			strBuff.append("<br>");
		}
		strBuff.append(MessageFormat.format(RB.getString("CertificateSerialNumber"), serialNo));
	}

	return strBuff.toString();
}
 
Example 13
Source Project: fabric-sdk-java   Source File: HFCAClientIT.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void testCertificateRevoke() throws Exception {

    SampleUser user = getTestUser(TEST_USER1_ORG);

    if (!user.isRegistered()) {
        RegistrationRequest rr = new RegistrationRequest(user.getName(), TEST_USER1_AFFILIATION);
        String password = "testUserRevoke";
        rr.setSecret(password);
        rr.addAttribute(new Attribute("user.role", "department lead"));
        rr.addAttribute(new Attribute(HFCAClient.HFCA_ATTRIBUTE_HFREVOKER, "true"));
        user.setEnrollmentSecret(client.register(rr, admin)); // Admin can register other users.
        if (!user.getEnrollmentSecret().equals(password)) {
            fail("Secret returned from RegistrationRequest not match : " + user.getEnrollmentSecret());
        }
    }

    if (!user.isEnrolled()) {
        EnrollmentRequest req = new EnrollmentRequest(DEFAULT_PROFILE_NAME, "label 2", null);
        req.addHost("example3.ibm.com");
        user.setEnrollment(client.enroll(user.getName(), user.getEnrollmentSecret(), req));
    }

    // verify
    String cert = user.getEnrollment().getCert();

    BufferedInputStream pem = new BufferedInputStream(new ByteArrayInputStream(cert.getBytes()));
    CertificateFactory certFactory = CertificateFactory.getInstance(Config.getConfig().getCertificateFormat());
    X509Certificate certificate = (X509Certificate) certFactory.generateCertificate(pem);

    // get its serial number
    String serial = DatatypeConverter.printHexBinary(certificate.getSerialNumber().toByteArray());

    // get its aki
    // 2.5.29.35 : AuthorityKeyIdentifier
    byte[] extensionValue = certificate.getExtensionValue(Extension.authorityKeyIdentifier.getId());
    ASN1OctetString akiOc = ASN1OctetString.getInstance(extensionValue);
    String aki = DatatypeConverter.printHexBinary(AuthorityKeyIdentifier.getInstance(akiOc.getOctets()).getKeyIdentifier());

    int startedWithRevokes = -1;

    if (!testConfig.isRunningAgainstFabric10()) {
        Thread.sleep(1000); //prevent clock skewing. make sure we request started with revokes.
        startedWithRevokes = getRevokes(null).length; //one more after we do this revoke.
        Thread.sleep(1000); //prevent clock skewing. make sure we request started with revokes.
    }

    // revoke all enrollment of this user
    client.revoke(admin, serial, aki, "revoke certificate");
    if (!testConfig.isRunningAgainstFabric10()) {

        final int newRevokes = getRevokes(null).length;

        assertEquals(format("Expected one more revocation %d, but got %d", startedWithRevokes + 1, newRevokes), startedWithRevokes + 1, newRevokes);
    }
}
 
Example 14
Source Project: keystore-explorer   Source File: X509Ext.java    License: GNU General Public License v3.0 4 votes vote down vote up
private String getAuthorityKeyIdentifierStringValue(byte[] value) throws IOException {
	// @formatter:off

	/*
	 * AuthorityKeyIdentifier ::= ASN1Sequence {
	 *   keyIdentifier [0] KeyIdentifier OPTIONAL,
	 *   authorityCertIssuer [1] GeneralNames OPTIONAL,
	 *   authorityCertSerialNumber [2] CertificateSerialNumber OPTIONAL
	 * }
	 *
	 * KeyIdentifier ::= OCTET STRING
	 *
	 * GeneralNames ::= ASN1Sequence SIZE (1..MAX) OF GeneralName
	 *
	 * CertificateSerialNumber ::= ASN1Integer
	 */

	// @formatter:on

	StringBuilder sb = new StringBuilder();

	AuthorityKeyIdentifier authorityKeyIdentifier = AuthorityKeyIdentifier.getInstance(value);

	byte[] keyIdentifier = authorityKeyIdentifier.getKeyIdentifier();
	GeneralNames authorityCertIssuer = authorityKeyIdentifier.getAuthorityCertIssuer();
	BigInteger certificateSerialNumber = authorityKeyIdentifier.getAuthorityCertSerialNumber();

	if (keyIdentifier != null) { // Optional
		// Output as a hex string
		sb.append(MessageFormat.format(res.getString("AuthorityKeyIdentifier"),
				HexUtil.getHexString(keyIdentifier)));
		sb.append(NEWLINE);
	}

	if (authorityCertIssuer != null) { // Optional
		sb.append(res.getString("CertificateIssuer"));
		sb.append(NEWLINE);

		for (GeneralName generalName : authorityCertIssuer.getNames()) {
			sb.append(INDENT);
			sb.append(GeneralNameUtil.toString(generalName));
			sb.append(NEWLINE);
		}
	}

	if (certificateSerialNumber != null) { // Optional
		// Output as an integer
		sb.append(MessageFormat.format(res.getString("CertificateSerialNumber"),
				HexUtil.getHexString(certificateSerialNumber)));
		sb.append(NEWLINE);
	}

	return sb.toString();
}
 
Example 15
private void addAuthorityKeyIdentifier(X509ExtensionSet extensionSet) throws CryptoException, IOException {
	KeyIdentifierGenerator akiGenerator = new KeyIdentifierGenerator(authorityPublicKey);
	AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(akiGenerator.generate160BitHashId());
	byte[] akiEncoded = wrapInOctetString(aki.getEncoded());
	extensionSet.addExtension(X509ExtensionType.AUTHORITY_KEY_IDENTIFIER.oid(), false, akiEncoded);
}
 
Example 16
Source Project: DeviceConnect-Android   Source File: SslUtil.java    License: MIT License 4 votes vote down vote up
/**
 * Generates a new, self-signed X509 V3 certificate for a KeyPair.
 *
 * @param  pair                      the {@link KeyPair} to be used
 * @param  name                      X.500 distinguished name
 * @param  notBefore                 not valid before this date
 * @param  notAfter                  not valid after this date
 * @param  serialNumber              serial number
 * @return                           the new certificate
 * @throws GeneralSecurityException  on error generating the certificate
 */
@SuppressWarnings("deprecation")
public static X509Certificate generateX509V3Certificate(KeyPair pair,
                                                        String name, Date notBefore, Date notAfter, BigInteger serialNumber)
        throws GeneralSecurityException {
    java.security.Security.addProvider(
            new org.bouncycastle.jce.provider.BouncyCastleProvider());
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    X509Name dnName = new X509Name(name);

    certGen.setSerialNumber(serialNumber);
    certGen.setIssuerDN(dnName);
    certGen.setSubjectDN(dnName);   // note: same as issuer
    certGen.setNotBefore(notBefore);
    certGen.setNotAfter(notAfter);
    certGen.setPublicKey(pair.getPublic());
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

    // For self-signed certificates, OpenSSL 0.9.6 has specific requirements
    // about certificate and extension content.  Quoting the `man verify`:
    //
    //   In OpenSSL 0.9.6 and later all certificates whose subject name matches
    //   the issuer name of the current certificate are subject to further
    //   tests. The relevant authority key identifier components of the current
    //   certificate (if present) must match the subject key identifier (if
    //   present) and issuer and serial number of the candidate issuer, in
    //   addition the keyUsage extension of the candidate issuer (if present)
    //   must permit certificate signing.
    //
    // In the code that follows,
    //   - the KeyUsage extension permits cert signing (KeyUsage.keyCertSign);
    //   - the Authority Key Identifier extension is added, matching the
    //     subject key identifier, and using the issuer, and serial number.
    certGen.addExtension(X509Extensions.BasicConstraints, true,
            new BasicConstraints(false));

    certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature
            | KeyUsage.keyEncipherment | KeyUsage.keyCertSign));
    certGen.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(
            KeyPurposeId.id_kp_serverAuth));
    AuthorityKeyIdentifier authIdentifier = createAuthorityKeyIdentifier(
            pair.getPublic(), dnName, serialNumber);

    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, true,
            authIdentifier);
    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, true,
            new SubjectKeyIdentifierStructure(pair.getPublic()));
    certGen.addExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(
            new GeneralName(GeneralName.rfc822Name, "[email protected]")));
    // This method is deprecated, but Android Eclair does not provide the
    // generate() methods.
    X509Certificate cert = certGen.generateX509Certificate(pair.getPrivate(), SecurityUtil.getSecurityProvider());
    return cert;
}
 
Example 17
Source Project: swift-k   Source File: AutoCA.java    License: Apache License 2.0 4 votes vote down vote up
private DEREncodable getAuthorityKeyIdentifier(PublicKey caPub) throws IOException {
    DERObject derKey = new ASN1InputStream(caPub.getEncoded()).readObject();
    return new AuthorityKeyIdentifier(new SubjectPublicKeyInfo((ASN1Sequence) derKey));
}
 
Example 18
Source Project: jqm   Source File: CertificateRequest.java    License: Apache License 2.0 4 votes vote down vote up
private void generateX509() throws Exception
{
    SecureRandom random = new SecureRandom();
    X500Name dnName = new X500Name(Subject);
    Calendar endValidity = Calendar.getInstance();
    endValidity.add(Calendar.YEAR, validityYear);

    SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());

    X509v3CertificateBuilder gen = new X509v3CertificateBuilder(
            authorityCertificate == null ? dnName : authorityCertificate.getSubject(),
            BigIntegers.createRandomInRange(BigInteger.ZERO, BigInteger.valueOf(Long.MAX_VALUE), random), new Date(),
            endValidity.getTime(), dnName, publicKeyInfo);

    // Public key ID
    DigestCalculator digCalc = new BcDigestCalculatorProvider().get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1));
    X509ExtensionUtils x509ExtensionUtils = new X509ExtensionUtils(digCalc);
    gen.addExtension(Extension.subjectKeyIdentifier, false, x509ExtensionUtils.createSubjectKeyIdentifier(publicKeyInfo));

    // EKU
    gen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(EKU));

    // Basic constraints (is CA?)
    if (authorityCertificate == null)
    {
        gen.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
    }

    // Key usage
    gen.addExtension(Extension.keyUsage, true, new KeyUsage(keyUsage));

    // Subject Alt names ?

    // Authority
    if (authorityCertificate != null)
    {
        gen.addExtension(Extension.authorityKeyIdentifier, false,
                new AuthorityKeyIdentifier(authorityCertificate.getSubjectPublicKeyInfo()));
    }

    // Signer
    ContentSigner signer = new JcaContentSignerBuilder("SHA512WithRSAEncryption").setProvider(Constants.JCA_PROVIDER)
            .build(authorityKey == null ? privateKey : authorityKey);

    // Go
    holder = gen.build(signer);
}
 
Example 19
Source Project: Spark   Source File: CertificateModel.java    License: Apache License 2.0 4 votes vote down vote up
private String authorityKeyIdentifierExtractor(ASN1Primitive primitive) {
	AuthorityKeyIdentifier authorityKeyIdentifier = AuthorityKeyIdentifier.getInstance(primitive);
	return Hex.toHexString(authorityKeyIdentifier.getKeyIdentifier());
}