/** * This method returns SKI bytes from certificate. * * @param certificateToken * {@code CertificateToken} * @param computeIfMissing * if the extension is missing and computeIfMissing = true, it will compute the SKI value from the Public * Key * @return ski bytes from the given certificate * @throws DSSException */ public static byte[] getSki(final CertificateToken certificateToken, boolean computeIfMissing) throws DSSException { try { byte[] sKI = certificateToken.getCertificate().getExtensionValue(Extension.subjectKeyIdentifier.getId()); if (Utils.isArrayNotEmpty(sKI)) { ASN1Primitive extension = X509ExtensionUtil.fromExtensionValue(sKI); SubjectKeyIdentifier skiBC = SubjectKeyIdentifier.getInstance(extension); return skiBC.getKeyIdentifier(); } else if (computeIfMissing) { // If extension not present, we compute it from the certificate public key DLSequence seq = (DLSequence) DERSequence.fromByteArray(certificateToken.getPublicKey().getEncoded()); DERBitString item = (DERBitString) seq.getObjectAt(1); return DSSUtils.digest(DigestAlgorithm.SHA1, item.getOctets()); } return null; } catch (Exception e) { throw new DSSException(e); } }
private SubjectPublicKeyInfo getSenderPublicKeyInfo(AlgorithmIdentifier recKeyAlgId, OriginatorIdentifierOrKey originator) throws CMSException, IOException { OriginatorPublicKey opk = originator.getOriginatorKey(); if (opk != null) { return getPublicKeyInfoFromOriginatorPublicKey(recKeyAlgId, opk); } OriginatorId origID; IssuerAndSerialNumber iAndSN = originator.getIssuerAndSerialNumber(); if (iAndSN != null) { origID = new OriginatorId(iAndSN.getName(), iAndSN.getSerialNumber().getValue()); } else { SubjectKeyIdentifier ski = originator.getSubjectKeyIdentifier(); origID = new OriginatorId(ski.getKeyIdentifier()); } return getPublicKeyInfoFromOriginatorId(origID); }
private String getSubjectKeyIndentifierStringValue(byte[] value) throws IOException { // @formatter:off /* * SubjectKeyIdentifier ::= KeyIdentifier * * KeyIdentifier ::= OCTET STRING */ // @formatter:on StringBuilder sb = new StringBuilder(); SubjectKeyIdentifier subjectKeyIdentifier = SubjectKeyIdentifier.getInstance(value); // Get key identifier from octet string byte[] keyIdentifierBytes = subjectKeyIdentifier.getKeyIdentifier(); sb.append(MessageFormat.format(res.getString("SubjectKeyIdentifier"), HexUtil.getHexString(keyIdentifierBytes))); sb.append(NEWLINE); return sb.toString(); }
private void okPressed() { byte[] keyIdentifier = jkiKeyIdentifier.getKeyIdentifier(); if (keyIdentifier == null) { JOptionPane.showMessageDialog(this, res.getString("DSubjectKeyIdentifier.ValueReq.message"), getTitle(), JOptionPane.WARNING_MESSAGE); return; } SubjectKeyIdentifier subjectKeyIdentifier = new SubjectKeyIdentifier(keyIdentifier); try { value = subjectKeyIdentifier.getEncoded(ASN1Encoding.DER); } catch (IOException ex) { DError dError = new DError(this, ex); dError.setLocationRelativeTo(this); dError.setVisible(true); return; } closeDialog(); }
/** * Certificate issued under an existing CA. * @param subjectDN the distinguished name of the subject. * @param subjectPublicKey the public key of the subject. * @param issuerCertificate the certificate of the issuer. * @param duration the validity duration of the certificate. * @param isCA * @param allUsage if isCA is true, add "regular" KeyUsage flags, for dual-use cert * @throws CertificateEncodingException * @throws IOException */ public MinimalCertificateGenerator(String subjectDN, PublicKey subjectPublicKey, X509Certificate issuerCertificate, long duration, boolean isCA, Integer chainLength, boolean allUsage) throws CertificateEncodingException, IOException { this(subjectDN, subjectPublicKey, issuerCertificate.getSubjectX500Principal(), duration, isCA, chainLength, allUsage); // Pull the existing subject identifier out of the issuer cert. byte [] subjectKeyID = issuerCertificate.getExtensionValue(X509Extensions.SubjectKeyIdentifier.toString()); if (null == subjectKeyID) { subjectKeyID = CryptoUtil.generateKeyID(subjectPublicKey); } else { // content of extension is wrapped in a DEROctetString DEROctetString content = (DEROctetString)CryptoUtil.decode(subjectKeyID); byte [] encapsulatedOctetString = content.getOctets(); DEROctetString octetStringKeyID = (DEROctetString)CryptoUtil.decode(encapsulatedOctetString); subjectKeyID = octetStringKeyID.getOctets(); } _aki = new AuthorityKeyIdentifier(subjectKeyID); }
public void performTest() throws IOException { SubjectPublicKeyInfo pubInfo = SubjectPublicKeyInfo.getInstance(ASN1Primitive.fromByteArray(pubKeyInfo)); SubjectKeyIdentifier ski = x509ExtensionUtils.createSubjectKeyIdentifier(pubInfo); if (!Arrays.areEqual(shaID, ski.getKeyIdentifier())) { fail("SHA-1 ID does not match"); } ski = x509ExtensionUtils.createTruncatedSubjectKeyIdentifier(pubInfo); if (!Arrays.areEqual(shaTruncID, ski.getKeyIdentifier())) { fail("truncated SHA-1 ID does not match"); } }
public void performTest() throws IOException { SubjectPublicKeyInfo pubInfo = SubjectPublicKeyInfo.getInstance(ASN1Primitive.fromByteArray(pubKeyInfo)); SubjectKeyIdentifier ski = SubjectKeyIdentifier.createSHA1KeyIdentifier(pubInfo); if (!Arrays.areEqual(shaID, ski.getKeyIdentifier())) { fail("SHA-1 ID does not match"); } ski = SubjectKeyIdentifier.createTruncatedSHA1KeyIdentifier(pubInfo); if (!Arrays.areEqual(shaTruncID, ski.getKeyIdentifier())) { fail("truncated SHA-1 ID does not match"); } }
public static X509Certificate generateCACertificate(String provider, X509Name subject, Date start, Date expired, KeyPair pair, int numberOfCAs, String signartureAlgorthm) throws InvalidKeyException, NoSuchProviderException, SignatureException, IOException { // generate the certificate X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(subject); certGen.setNotBefore(start); certGen.setNotAfter(expired); certGen.setSubjectDN(subject); certGen.setPublicKey(pair.getPublic()); certGen.setSignatureAlgorithm(signartureAlgorthm); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(numberOfCAs)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign)); SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo((ASN1Sequence) new DERInputStream( new ByteArrayInputStream(pair.getPublic().getEncoded())).readObject()); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifier(spki)); SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo((ASN1Sequence) new DERInputStream( new ByteArrayInputStream(pair.getPublic().getEncoded())).readObject()); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifier(apki)); return certGen.generateX509Certificate(pair.getPrivate(), provider); }
public static X509Certificate generateCACertificate(String provider, X509Name subject, Date start, Date expired, KeyPair pair, int numberOfCAs, String signatureAlgorthm) throws CertificateEncodingException, IllegalStateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, InvalidKeyException, IOException { // generate the certificate X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(subject); certGen.setNotBefore(start); certGen.setNotAfter(expired); certGen.setSubjectDN(subject); certGen.setPublicKey(pair.getPublic()); certGen.setSignatureAlgorithm(signatureAlgorthm); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(numberOfCAs)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign)); SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo((ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pair.getPublic().getEncoded())).readObject()); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifier(spki)); SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo((ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pair.getPublic().getEncoded())).readObject()); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifier(apki)); return certGen.generate(pair.getPrivate(), provider); }
private static ASN1OctetString fromPublicKey( PublicKey pubKey) throws InvalidKeyException { try { SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(pubKey.getEncoded()); return (ASN1OctetString)(new SubjectKeyIdentifier(info).toASN1Object()); } catch (Exception e) { throw new InvalidKeyException("Exception extracting key details: " + e.toString()); } }
/** * Return a RFC 3280 type 2 key identifier. As in: * <pre> * (2) The keyIdentifier is composed of a four bit type field with * the value 0100 followed by the least significant 60 bits of the * SHA-1 hash of the value of the BIT STRING subjectPublicKey. * </pre> * @param publicKeyInfo the key info object containing the subjectPublicKey field. * @return the key identifier. */ public SubjectKeyIdentifier createTruncatedSubjectKeyIdentifier(SubjectPublicKeyInfo publicKeyInfo) { byte[] digest = calculateIdentifier(publicKeyInfo); byte[] id = new byte[8]; System.arraycopy(digest, digest.length - 8, id, 0, id.length); id[0] &= 0x0f; id[0] |= 0x40; return new SubjectKeyIdentifier(id); }
/** * return an OriginatorIdentifierOrKey object from the given object. * * @param o the object we want converted. * @exception IllegalArgumentException if the object cannot be converted. */ public static OriginatorIdentifierOrKey getInstance( Object o) { if (o == null || o instanceof OriginatorIdentifierOrKey) { return (OriginatorIdentifierOrKey)o; } if (o instanceof IssuerAndSerialNumber) { return new OriginatorIdentifierOrKey((IssuerAndSerialNumber)o); } if (o instanceof SubjectKeyIdentifier) { return new OriginatorIdentifierOrKey((SubjectKeyIdentifier)o); } if (o instanceof OriginatorPublicKey) { return new OriginatorIdentifierOrKey((OriginatorPublicKey)o); } if (o instanceof ASN1TaggedObject) { // TODO Add validation return new OriginatorIdentifierOrKey((ASN1TaggedObject)o); } throw new IllegalArgumentException("Invalid OriginatorIdentifierOrKey: " + o.getClass().getName()); }
public SubjectKeyIdentifier getSubjectKeyIdentifier() { if (id instanceof ASN1TaggedObject && ((ASN1TaggedObject)id).getTagNo() == 0) { return SubjectKeyIdentifier.getInstance((ASN1TaggedObject)id, false); } return null; }
private SubjectKeyIdentifier createSubjectKeyId( PublicKey pubKey) { try { SubjectPublicKeyInfo info = new SubjectPublicKeyInfo( (ASN1Sequence)ASN1Primitive.fromByteArray(pubKey.getEncoded())); return new SubjectKeyIdentifier(info); } catch (Exception e) { throw new RuntimeException("error creating key"); } }
/** * Return a RFC 5280 type 2 key identifier. As in: * <pre> * (2) The keyIdentifier is composed of a four bit type field with * the value 0100 followed by the least significant 60 bits of the * SHA-1 hash of the value of the BIT STRING subjectPublicKey. * </pre> * @param publicKeyInfo the key info object containing the subjectPublicKey field. * @return the key identifier. */ public SubjectKeyIdentifier createTruncatedSubjectKeyIdentifier(SubjectPublicKeyInfo publicKeyInfo) { byte[] digest = calculateIdentifier(publicKeyInfo); byte[] id = new byte[8]; System.arraycopy(digest, digest.length - 8, id, 0, id.length); id[0] &= 0x0f; id[0] |= 0x40; return new SubjectKeyIdentifier(id); }
private byte[] getSubjectKeyIdentifier() { SubjectKeyIdentifier subId = SubjectKeyIdentifier.fromExtensions(certificateHolders[0].getExtensions()); if (subId == null) { return null; } return subId.getKeyIdentifier(); }
/** * Return an OriginatorIdentifierOrKey object from the given object. * <p> * Accepted inputs: * <ul> * <li> null → null * <li> {@link OriginatorIdentifierOrKey} object * <li> {@link IssuerAndSerialNumber} object * <li> {@link org.bouncycastle.asn1.ASN1TaggedObject#getInstance(java.lang.Object) ASN1TaggedObject} input formats with IssuerAndSerialNumber structure inside * </ul> * * @param o the object we want converted. * @exception IllegalArgumentException if the object cannot be converted. */ public static OriginatorIdentifierOrKey getInstance( Object o) { if (o == null || o instanceof OriginatorIdentifierOrKey) { return (OriginatorIdentifierOrKey)o; } if (o instanceof IssuerAndSerialNumber || o instanceof ASN1Sequence) { return new OriginatorIdentifierOrKey(IssuerAndSerialNumber.getInstance(o)); } if (o instanceof ASN1TaggedObject) { ASN1TaggedObject tagged = (ASN1TaggedObject)o; if (tagged.getTagNo() == 0) { return new OriginatorIdentifierOrKey(SubjectKeyIdentifier.getInstance(tagged, false)); } else if (tagged.getTagNo() == 1) { return new OriginatorIdentifierOrKey(OriginatorPublicKey.getInstance(tagged, false)); } } throw new IllegalArgumentException("Invalid OriginatorIdentifierOrKey: " + o.getClass().getName()); }
public static SubjectKeyIdentifier createSubjectKeyIdentifier(Key key) throws IOException { try (ASN1InputStream is = new ASN1InputStream(new ByteArrayInputStream(key.getEncoded()))) { ASN1Sequence seq = (ASN1Sequence) is.readObject(); SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(seq); return new BcX509ExtensionUtils().createSubjectKeyIdentifier(info); } }
private static PKCS12SafeBagBuilder createCRTSafeBagBuilder(String alias, X509Certificate crt, boolean addKeyId) throws IOException, GeneralSecurityException { PKCS12SafeBagBuilder safeBagBuilder = new JcaPKCS12SafeBagBuilder(crt); safeBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(alias)); if (addKeyId) { JcaX509ExtensionUtils extensionUtils = new JcaX509ExtensionUtils(); SubjectKeyIdentifier subjectKeyIdentifier = extensionUtils.createSubjectKeyIdentifier(crt.getPublicKey()); safeBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, subjectKeyIdentifier); } return safeBagBuilder; }
private static PKCS12SafeBagBuilder createKeySafeBagBuilder(String alias, KeyPair key) throws GeneralSecurityException { PKCS12SafeBagBuilder safeBagBuilder = new JcaPKCS12SafeBagBuilder(key.getPrivate()); safeBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(alias)); JcaX509ExtensionUtils extensionUtils = new JcaX509ExtensionUtils(); SubjectKeyIdentifier subjectKeyIdentifier = extensionUtils.createSubjectKeyIdentifier(key.getPublic()); safeBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, subjectKeyIdentifier); return safeBagBuilder; }
private static PKCS12SafeBagBuilder createKeySafeBagBuilder(String alias, KeyPair key, char[] passwordChars) throws GeneralSecurityException { PKCS12SafeBagBuilder safeBagBuilder = new JcaPKCS12SafeBagBuilder(key.getPrivate(), PKCS12_ENCRYPTOR_BUILDER.build(passwordChars)); safeBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(alias)); JcaX509ExtensionUtils extensionUtils = new JcaX509ExtensionUtils(); SubjectKeyIdentifier subjectKeyIdentifier = extensionUtils.createSubjectKeyIdentifier(key.getPublic()); safeBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, subjectKeyIdentifier); return safeBagBuilder; }
private SubjectKeyIdentifier createSubjectKeyId( PublicKey pubKey) { try { SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(pubKey.getEncoded()); return new SubjectKeyIdentifier(getDigest(info)); } catch (Exception e) { throw new RuntimeException("error creating key"); } }
X509Certificate getSelfSigned(KeyPair keyPair, CertificateGenerationParameters params) throws Exception { SubjectKeyIdentifier keyIdentifier = getSubjectKeyIdentifierFromKeyInfo(keyPair.getPublic()); return getSignedByIssuer( null, keyPair.getPrivate(), params.getX500Principal(), keyIdentifier, keyPair, params ); }
private X509Certificate generateSelfSignedCertificate(KeyPair keyPair, String subjectDn, DateTime notBefore, DateTime notAfter) throws IOException, InvalidKeyException, IllegalStateException, NoSuchAlgorithmException, SignatureException, CertificateException { PublicKey subjectPublicKey = keyPair.getPublic(); PrivateKey issuerPrivateKey = keyPair.getPrivate(); String signatureAlgorithm = "SHA1WithRSAEncryption"; X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator(); certificateGenerator.reset(); certificateGenerator.setPublicKey(subjectPublicKey); certificateGenerator.setSignatureAlgorithm(signatureAlgorithm); certificateGenerator.setNotBefore(notBefore.toDate()); certificateGenerator.setNotAfter(notAfter.toDate()); X509Principal issuerDN = new X509Principal(subjectDn); certificateGenerator.setIssuerDN(issuerDN); certificateGenerator.setSubjectDN(new X509Principal(subjectDn)); certificateGenerator.setSerialNumber(new BigInteger(128, new SecureRandom())); certificateGenerator.addExtension(X509Extensions.SubjectKeyIdentifier, false, createSubjectKeyId(subjectPublicKey)); PublicKey issuerPublicKey; issuerPublicKey = subjectPublicKey; certificateGenerator.addExtension(X509Extensions.AuthorityKeyIdentifier, false, createAuthorityKeyId(issuerPublicKey)); certificateGenerator.addExtension(X509Extensions.BasicConstraints, false, new BasicConstraints(true)); X509Certificate certificate; certificate = certificateGenerator.generate(issuerPrivateKey); /* * Next certificate factory trick is needed to make sure that the * certificate delivered to the caller is provided by the default * security provider instead of BouncyCastle. If we don't do this trick * we might run into trouble when trying to use the CertPath validator. */ CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); certificate = (X509Certificate) certificateFactory .generateCertificate(new ByteArrayInputStream(certificate.getEncoded())); return certificate; }
private byte[] getSubjectKeyId(X509Certificate cert) throws IOException { byte[] extvalue = cert.getExtensionValue(X509Extensions.SubjectKeyIdentifier.getId()); if (extvalue == null) { return null; } ASN1OctetString str = ASN1OctetString .getInstance(new ASN1InputStream(new ByteArrayInputStream(extvalue)).readObject()); SubjectKeyIdentifier keyId = SubjectKeyIdentifier .getInstance(new ASN1InputStream(new ByteArrayInputStream(str.getOctets())).readObject()); return keyId.getKeyIdentifier(); }