org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers Java Examples

The following examples show how to use org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers. 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: CAdESSignature.java    From dss with GNU Lesser General Public License v2.1 7 votes vote down vote up
private SignerAttribute getSignerAttributeV1() {
	final Attribute id_aa_ets_signerAttr = getSignedAttribute(PKCSObjectIdentifiers.id_aa_ets_signerAttr);
	if (id_aa_ets_signerAttr != null) {
		final ASN1Set attrValues = id_aa_ets_signerAttr.getAttrValues();
		final ASN1Encodable attrValue = attrValues.getObjectAt(0);
		try {
			return SignerAttribute.getInstance(attrValue);
		} catch (Exception e) {
			String warningMessage = "Unable to parse signerAttr - [{}]. Reason : {}";
			if (LOG.isDebugEnabled()) {
				LOG.warn(warningMessage, Utils.toBase64(DSSASN1Utils.getDEREncoded(attrValue)), e.getMessage(), e);
			} else {
				LOG.warn(warningMessage, Utils.toBase64(DSSASN1Utils.getDEREncoded(attrValue)), e.getMessage());
			}
		}
	}
	return null;
}
 
Example #2
Source File: AlgorithmUtil.java    From xipki with Apache License 2.0 6 votes vote down vote up
public static boolean isRSASigAlgId(AlgorithmIdentifier algId) {
  ASN1ObjectIdentifier oid = Args.notNull(algId, "algId").getAlgorithm();
  if (PKCSObjectIdentifiers.sha1WithRSAEncryption.equals(oid)
      || PKCSObjectIdentifiers.sha224WithRSAEncryption.equals(oid)
      || PKCSObjectIdentifiers.sha256WithRSAEncryption.equals(oid)
      || PKCSObjectIdentifiers.sha384WithRSAEncryption.equals(oid)
      || PKCSObjectIdentifiers.sha512WithRSAEncryption.equals(oid)
      || NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_224.equals(oid)
      || NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_256.equals(oid)
      || NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_384.equals(oid)
      || NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_512.equals(oid)
      || PKCSObjectIdentifiers.id_RSASSA_PSS.equals(oid)) {
    return true;
  }

  return false;
}
 
Example #3
Source File: TimeStampValidatorImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public void validateTimeStampToken(byte[] bs, TimeStampToken tsToken) throws InvalidTimeStampException, TechnicalConnectorException {
   byte[] calculatedDigest = ConnectorCryptoUtils.calculateDigest(tsToken.getTimeStampInfo().getMessageImprintAlgOID().getId(), bs);
   byte[] tokenDigestValue = tsToken.getTimeStampInfo().getMessageImprintDigest();
   if (!MessageDigest.isEqual(calculatedDigest, tokenDigestValue)) {
      throw new InvalidTimeStampException("Response for different message imprint digest.");
   } else {
      Attribute scV1 = tsToken.getSignedAttributes().get(PKCSObjectIdentifiers.id_aa_signingCertificate);
      Attribute scV2 = tsToken.getSignedAttributes().get(PKCSObjectIdentifiers.id_aa_signingCertificateV2);
      if (scV1 == null && scV2 == null) {
         throw new InvalidTimeStampException("no signing certificate attribute present.", (Exception)null);
      } else if (scV1 != null && scV2 != null) {
         throw new InvalidTimeStampException("Conflicting signing certificate attributes present.");
      } else {
         this.validateTimeStampToken(tsToken);
      }
   }
}
 
Example #4
Source File: AlgorithmUtil.java    From xipki with Apache License 2.0 6 votes vote down vote up
public static String getSignatureAlgoName(AlgorithmIdentifier sigAlgId)
    throws NoSuchAlgorithmException {
  ASN1ObjectIdentifier algOid = Args.notNull(sigAlgId, "sigAlgId").getAlgorithm();
  String name = null;
  if (PKCSObjectIdentifiers.id_RSASSA_PSS.equals(algOid)) {
    RSASSAPSSparams param = RSASSAPSSparams.getInstance(sigAlgId.getParameters());
    ASN1ObjectIdentifier digestAlgOid = param.getHashAlgorithm().getAlgorithm();
    name = digestOidToMgf1SigNameMap.get(digestAlgOid);
    if (name == null) {
      throw new NoSuchAlgorithmException("unsupported digest algorithm " + digestAlgOid);
    }
  } else {
    name = sigAlgOidToNameMap.get(algOid);
  }

  if (name == null) {
    throw new NoSuchAlgorithmException("unsupported signature algorithm " + algOid.getId());
  }
  return name;
}
 
Example #5
Source File: TimeStampValidatorImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public void validateTimeStampToken(byte[] bs, TimeStampToken tsToken) throws InvalidTimeStampException, TechnicalConnectorException {
   byte[] calculatedDigest = ConnectorCryptoUtils.calculateDigest(tsToken.getTimeStampInfo().getMessageImprintAlgOID().getId(), bs);
   byte[] tokenDigestValue = tsToken.getTimeStampInfo().getMessageImprintDigest();
   if (!MessageDigest.isEqual(calculatedDigest, tokenDigestValue)) {
      throw new InvalidTimeStampException("Response for different message imprint digest.");
   } else {
      Attribute scV1 = tsToken.getSignedAttributes().get(PKCSObjectIdentifiers.id_aa_signingCertificate);
      Attribute scV2 = tsToken.getSignedAttributes().get(PKCSObjectIdentifiers.id_aa_signingCertificateV2);
      if (scV1 == null && scV2 == null) {
         throw new InvalidTimeStampException("no signing certificate attribute present.", (Exception)null);
      } else if (scV1 != null && scV2 != null) {
         throw new InvalidTimeStampException("Conflicting signing certificate attributes present.");
      } else {
         this.validateTimeStampToken(tsToken);
      }
   }
}
 
Example #6
Source File: AbstractRequirementChecks.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
@BeforeEach
public void init() throws Exception {
	DSSDocument signedDocument = getSignedDocument();

	ASN1InputStream asn1sInput = new ASN1InputStream(signedDocument.openStream());
	ASN1Sequence asn1Seq = (ASN1Sequence) asn1sInput.readObject();
	assertEquals(2, asn1Seq.size());
	ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(asn1Seq.getObjectAt(0));
	assertEquals(PKCSObjectIdentifiers.signedData, oid);

	ASN1TaggedObject taggedObj = ASN1TaggedObject.getInstance(asn1Seq.getObjectAt(1));
	signedData = SignedData.getInstance(taggedObj.getObject());

	ASN1Set signerInfosAsn1 = signedData.getSignerInfos();
	assertEquals(1, signerInfosAsn1.size());

	signerInfo = SignerInfo.getInstance(ASN1Sequence.getInstance(signerInfosAsn1.getObjectAt(0)));

	Utils.closeQuietly(asn1sInput);
}
 
Example #7
Source File: AlgorithmUtil.java    From xipki with Apache License 2.0 6 votes vote down vote up
public static AlgorithmIdentifier extractDigesetAlgFromSigAlg(AlgorithmIdentifier sigAlgId)
    throws NoSuchAlgorithmException {
  ASN1ObjectIdentifier algOid = sigAlgId.getAlgorithm();

  ASN1ObjectIdentifier digestAlgOid;
  if (PKCSObjectIdentifiers.id_RSASSA_PSS.equals(algOid)) {
    ASN1Encodable asn1Encodable = sigAlgId.getParameters();
    RSASSAPSSparams param = RSASSAPSSparams.getInstance(asn1Encodable);
    digestAlgOid = param.getHashAlgorithm().getAlgorithm();
  } else {
    HashAlgo digestAlg = sigAlgOidToDigestMap.get(algOid);
    if (digestAlg == null) {
      throw new NoSuchAlgorithmException("unknown signature algorithm " + algOid.getId());
    }
    digestAlgOid = digestAlg.getOid();
  }

  return new AlgorithmIdentifier(digestAlgOid, DERNull.INSTANCE);
}
 
Example #8
Source File: SignatureCmpCaClient.java    From xipki with Apache License 2.0 6 votes vote down vote up
public SignatureCmpCaClient(String caUri, X509Certificate caCert, PrivateKey requestorKey,
    X509Certificate requestorCert, X509Certificate responderCert, String hashAlgo)
    throws Exception {
  super(caUri, caCert,
      X500Name.getInstance(requestorCert.getSubjectX500Principal().getEncoded()),
      X500Name.getInstance(responderCert.getSubjectX500Principal().getEncoded()),
      hashAlgo);

  this.requestorKey = SdkUtil.requireNonNull("requestorKey", requestorKey);
  SdkUtil.requireNonNull("requestorCert", requestorCert);

  this.responderCert = SdkUtil.requireNonNull("responderCert", responderCert);
  this.requestorSigner = buildSigner(requestorKey);

  ASN1ObjectIdentifier[] oids = {PKCSObjectIdentifiers.sha256WithRSAEncryption,
    PKCSObjectIdentifiers.sha384WithRSAEncryption, PKCSObjectIdentifiers.sha512WithRSAEncryption,
    X9ObjectIdentifiers.ecdsa_with_SHA256, X9ObjectIdentifiers.ecdsa_with_SHA384,
    X9ObjectIdentifiers.ecdsa_with_SHA512, NISTObjectIdentifiers.dsa_with_sha256,
    NISTObjectIdentifiers.dsa_with_sha384, NISTObjectIdentifiers.dsa_with_sha512};
  for (ASN1ObjectIdentifier oid : oids) {
    trustedProtectionAlgOids.add(oid.getId());
  }
}
 
Example #9
Source File: TestDefaultProfile.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
/**
 * Generates an CSR with the extension specified.
 * This function is used to get an Invalid CSR and test that PKI profile
 * rejects these invalid extensions, Hence the function name, by itself it
 * is a well formed CSR, but our PKI profile will treat it as invalid CSR.
 *
 * @param kPair - Key Pair.
 * @return CSR  - PKCS10CertificationRequest
 * @throws OperatorCreationException - on Error.
 */
private PKCS10CertificationRequest getInvalidCSR(KeyPair kPair,
    Extensions extensions) throws OperatorCreationException {
  X500NameBuilder namebuilder =
      new X500NameBuilder(X500Name.getDefaultStyle());
  namebuilder.addRDN(BCStyle.CN, "invalidCert");
  PKCS10CertificationRequestBuilder p10Builder =
      new JcaPKCS10CertificationRequestBuilder(namebuilder.build(),
          keyPair.getPublic());
  p10Builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest,
      extensions);
  JcaContentSignerBuilder csBuilder =
      new JcaContentSignerBuilder(this.securityConfig.getSignatureAlgo());
  ContentSigner signer = csBuilder.build(keyPair.getPrivate());
  return p10Builder.build(signer);
}
 
Example #10
Source File: CertificateSignRequest.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
private PKCS10CertificationRequest generateCSR() throws
    OperatorCreationException {
  X500Name dnName = SecurityUtil.getDistinguishedName(subject, scmID,
      clusterID);
  PKCS10CertificationRequestBuilder p10Builder =
      new JcaPKCS10CertificationRequestBuilder(dnName, keyPair.getPublic());

  ContentSigner contentSigner =
      new JcaContentSignerBuilder(config.getSignatureAlgo())
          .setProvider(config.getProvider())
          .build(keyPair.getPrivate());

  if (extensions != null) {
    p10Builder.addAttribute(
        PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extensions);
  }
  return p10Builder.build(contentSigner);
}
 
Example #11
Source File: AlgorithmUtil.java    From xipki with Apache License 2.0 6 votes vote down vote up
public static AlgorithmCode getSigOrMacAlgoCode(AlgorithmIdentifier algId)
    throws NoSuchAlgorithmException {
  ASN1ObjectIdentifier oid = algId.getAlgorithm();
  AlgorithmCode code = algOidToCodeMap.get(oid);
  if (code != null) {
    return code;
  }

  if (PKCSObjectIdentifiers.id_RSASSA_PSS.equals(oid)) {
    RSASSAPSSparams param = RSASSAPSSparams.getInstance(algId.getParameters());
    ASN1ObjectIdentifier digestAlgOid = param.getHashAlgorithm().getAlgorithm();
    code = digestToMgf1AlgCodeMap.get(digestAlgOid);
    if (code == null) {
      throw new NoSuchAlgorithmException("unsupported digest algorithm " + digestAlgOid);
    }
    return code;
  } else {
    throw new NoSuchAlgorithmException("unsupported signature algorithm " + oid.getId());
  }
}
 
Example #12
Source File: SM2CertUtil.java    From gmhelper with Apache License 2.0 6 votes vote down vote up
public static BCECPrivateKey getPrivateKeyFromPfx(byte[] pfxDER, String passwd) throws Exception {
    InputDecryptorProvider inputDecryptorProvider = new JcePKCSPBEInputDecryptorProviderBuilder()
        .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(passwd.toCharArray());
    PKCS12PfxPdu pfx = new PKCS12PfxPdu(pfxDER);

    ContentInfo[] infos = pfx.getContentInfos();
    if (infos.length != 2) {
        throw new Exception("Only support one pair ContentInfo");
    }

    for (int i = 0; i != infos.length; i++) {
        if (!infos[i].getContentType().equals(PKCSObjectIdentifiers.encryptedData)) {
            PKCS12SafeBagFactory dataFact = new PKCS12SafeBagFactory(infos[i]);
            PKCS12SafeBag[] bags = dataFact.getSafeBags();
            PKCS8EncryptedPrivateKeyInfo encInfo = (PKCS8EncryptedPrivateKeyInfo) bags[0].getBagValue();
            PrivateKeyInfo info = encInfo.decryptPrivateKeyInfo(inputDecryptorProvider);
            BCECPrivateKey privateKey = BCECUtil.convertPKCS8ToECPrivateKey(info.getEncoded());
            return privateKey;
        }
    }

    throw new Exception("Not found Private Key in this pfx");
}
 
Example #13
Source File: P12ContentSignerBuilder.java    From xipki with Apache License 2.0 6 votes vote down vote up
protected Signer createSigner(AlgorithmIdentifier sigAlgId, AlgorithmIdentifier digAlgId)
    throws OperatorCreationException {
  if (!AlgorithmUtil.isRSASigAlgId(sigAlgId)) {
    throw new OperatorCreationException("the given algorithm is not a valid RSA signature "
        + "algirthm '" + sigAlgId.getAlgorithm().getId() + "'");
  }

  if (!PKCSObjectIdentifiers.id_RSASSA_PSS.equals(sigAlgId.getAlgorithm())) {
    Digest dig = digestProvider.get(digAlgId);
    return new RSADigestSigner(dig);
  }

  try {
    return SignerUtil.createPSSRSASigner(sigAlgId);
  } catch (XiSecurityException ex) {
    throw new OperatorCreationException(ex.getMessage(), ex);
  }
}
 
Example #14
Source File: TlsHelperTest.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
private List<String> extractSanFromCsr(JcaPKCS10CertificationRequest csr) {
    List<String> sans = new ArrayList<>();
    Attribute[] certAttributes = csr.getAttributes();
    for (Attribute attribute : certAttributes) {
        if (attribute.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
            Extensions extensions = Extensions.getInstance(attribute.getAttrValues().getObjectAt(0));
            GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName);
            GeneralName[] names = gns.getNames();
            for (GeneralName name : names) {
                logger.info("Type: " + name.getTagNo() + " | Name: " + name.getName());
                String title = "";
                if (name.getTagNo() == GeneralName.dNSName) {
                    title = "DNS";
                } else if (name.getTagNo() == GeneralName.iPAddress) {
                    title = "IP Address";
                    // name.toASN1Primitive();
                } else if (name.getTagNo() == GeneralName.otherName) {
                    title = "Other Name";
                }
                sans.add(title + ": " + name.getName());
            }
        }
    }

    return sans;
}
 
Example #15
Source File: CertificateUtils.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Extract extensions from CSR object
 */
public static Extensions getExtensionsFromCSR(JcaPKCS10CertificationRequest csr) {
    Attribute[] attributess = csr.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
    for (Attribute attribute : attributess) {
        ASN1Set attValue = attribute.getAttrValues();
        if (attValue != null) {
            ASN1Encodable extension = attValue.getObjectAt(0);
            if (extension instanceof Extensions) {
                return (Extensions) extension;
            } else if (extension instanceof DERSequence) {
                return Extensions.getInstance(extension);
            }
        }
    }
    return null;
}
 
Example #16
Source File: CertificateUtils.java    From nifi-registry with Apache License 2.0 6 votes vote down vote up
/**
 * Extract extensions from CSR object
 */
public static Extensions getExtensionsFromCSR(JcaPKCS10CertificationRequest csr) {
    Attribute[] attributess = csr.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
    for (Attribute attribute : attributess) {
        ASN1Set attValue = attribute.getAttrValues();
        if (attValue != null) {
            ASN1Encodable extension = attValue.getObjectAt(0);
            if (extension instanceof Extensions) {
                return (Extensions) extension;
            } else if (extension instanceof DERSequence) {
                return Extensions.getInstance(extension);
            }
        }
    }
    return null;
}
 
Example #17
Source File: SM2CertUtil.java    From gmhelper with Apache License 2.0 6 votes vote down vote up
public static X509Certificate getX509CertificateFromPfx(byte[] pfxDER, String passwd) throws Exception {
    InputDecryptorProvider inputDecryptorProvider = new JcePKCSPBEInputDecryptorProviderBuilder()
        .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(passwd.toCharArray());
    PKCS12PfxPdu pfx = new PKCS12PfxPdu(pfxDER);

    ContentInfo[] infos = pfx.getContentInfos();
    if (infos.length != 2) {
        throw new Exception("Only support one pair ContentInfo");
    }

    for (int i = 0; i != infos.length; i++) {
        if (infos[i].getContentType().equals(PKCSObjectIdentifiers.encryptedData)) {
            PKCS12SafeBagFactory dataFact = new PKCS12SafeBagFactory(infos[i], inputDecryptorProvider);
            PKCS12SafeBag[] bags = dataFact.getSafeBags();
            X509CertificateHolder certHoler = (X509CertificateHolder) bags[0].getBagValue();
            return SM2CertUtil.getX509Certificate(certHoler.getEncoded());
        }
    }

    throw new Exception("Not found X509Certificate in this pfx");
}
 
Example #18
Source File: CAdESTimeStampSigner.java    From signer with GNU Lesser General Public License v3.0 6 votes vote down vote up
private byte[] doTimeStamp (byte[] content, byte[] hash){
	try {
		AttributeFactory attributeFactory = AttributeFactory.getInstance();

		SignedOrUnsignedAttribute signedOrUnsignedAttribute = attributeFactory
				.factory(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken
						.getId());
		if (content != null){
			signedOrUnsignedAttribute.initialize(this.pkcs1.getPrivateKey(),
					this.getCertificateChain(), content, signaturePolicy, null);
		}else{
			signedOrUnsignedAttribute.initialize(this.pkcs1.getPrivateKey(),
					this.getCertificateChain(), null, signaturePolicy, hash);
		}			
		byte[] result = signedOrUnsignedAttribute.getValue().getEncoded();
		return result;
	} catch (IOException ex) {
		throw new SignerException(ex.getMessage());
	}
}
 
Example #19
Source File: CMSSignedDataWrapper.java    From Websocket-Smart-Card-Signer with GNU Affero General Public License v3.0 6 votes vote down vote up
private static ASN1Set buildSignedAttributes(byte[] hash, Date dateTime, X509Certificate cert) throws Exception {
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(new Attribute(CMSAttributes.contentType, new DERSet(PKCSObjectIdentifiers.data)));
    if (dateTime != null)
        v.add(new Attribute(CMSAttributes.signingTime, new DERSet(new Time(dateTime))));
    v.add(new Attribute(CMSAttributes.messageDigest, new DERSet(new DEROctetString(hash))));

    // CADES support section
    ASN1EncodableVector aaV2 = new ASN1EncodableVector();
    AlgorithmIdentifier algoId = new AlgorithmIdentifier(new ASN1ObjectIdentifier(CMSSignedDataGenerator.DIGEST_SHA256), null);
    aaV2.add(algoId);
    byte[] dig = SignUtils.calculateHASH(CMSSignedDataGenerator.DIGEST_SHA256, cert.getEncoded());
    aaV2.add(new DEROctetString(dig));
    Attribute cades = new Attribute(PKCSObjectIdentifiers.id_aa_signingCertificateV2, new DERSet(new DERSequence(new DERSequence(new DERSequence(aaV2)))));
    v.add(cades);

    ASN1Set signedAttributes = new DERSet(v);
    return signedAttributes;
}
 
Example #20
Source File: JarSigner.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
private static CMSSignedData addTimestamp(String tsaUrl, CMSSignedData signedData) throws IOException {

		Collection<SignerInformation> signerInfos = signedData.getSignerInfos().getSigners();

		// get signature of first signer (should be the only one)
		SignerInformation si = signerInfos.iterator().next();
		byte[] signature = si.getSignature();

		// send request to TSA
		byte[] token = TimeStampingClient.getTimeStampToken(tsaUrl, signature, DigestType.SHA1);

		// create new SignerInformation with TS attribute
		Attribute tokenAttr = new Attribute(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken,
				new DERSet(ASN1Primitive.fromByteArray(token)));
		ASN1EncodableVector timestampVector = new ASN1EncodableVector();
		timestampVector.add(tokenAttr);
		AttributeTable at = new AttributeTable(timestampVector);
		si = SignerInformation.replaceUnsignedAttributes(si, at);
		signerInfos.clear();
		signerInfos.add(si);
		SignerInformationStore newSignerStore = new SignerInformationStore(signerInfos);

		// create new signed data
		CMSSignedData newSignedData = CMSSignedData.replaceSigners(signedData, newSignerStore);
		return newSignedData;
	}
 
Example #21
Source File: CalculateDigest.java    From testarea-pdfbox2 with Apache License 2.0 6 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/57926872/signed-pdf-content-digest-that-was-calculated-during-verification-is-diffrent-th">
 * Signed PDF content digest that was calculated during verification is diffrent than decripted digest from signature
 * </a>
 * <br/>
 * <a href="https://drive.google.com/open?id=1UlOZOp-UYllK7Ra35dggccoWdhcb_Ntp">
 * TEST-signed-pades-baseline-b.pdf
 * </a>
 * <p>
 * The code here demonstrates how to retrieve the messageDigest
 * signed attribute value from a signed PDF. For production use
 * obviously some null checks are required.
 * </p>
 */
@Test
public void testExtractMessageDigestAttributeForUser2893427() throws IOException, CMSException {
    try (   InputStream resource = getClass().getResourceAsStream("TEST-signed-pades-baseline-b.pdf")   ) {
        byte[] bytes = IOUtils.toByteArray(resource);
        PDDocument document = Loader.loadPDF(bytes);
        List<PDSignature> signatures = document.getSignatureDictionaries();
        PDSignature sig = signatures.get(0);
        byte[] cmsBytes = sig.getContents(bytes);
        CMSSignedData cms = new CMSSignedData(cmsBytes);
        SignerInformation signerInformation = cms.getSignerInfos().iterator().next();
        Attribute attribute = signerInformation.getSignedAttributes().get(PKCSObjectIdentifiers.pkcs_9_at_messageDigest);
        ASN1Encodable value = attribute.getAttributeValues()[0];
        System.out.printf("MessageDigest attribute value: %s\n", value);
    }
}
 
Example #22
Source File: KeypairGenControl.java    From xipki with Apache License 2.0 5 votes vote down vote up
public RSAKeypairGenControl(int keysize, BigInteger publicExponent,
    ASN1ObjectIdentifier keyAlgorithmOid) {
  if (keysize < 1024 || keysize % 512 != 0) {
    throw new IllegalArgumentException("invalid keysize " + keysize);
  }

  this.keysize = keysize;
  this.publicExponent = (publicExponent != null) ? publicExponent
      : BigInteger.valueOf(0x10001);
  this.keyAlgorithm = new AlgorithmIdentifier(
      (keyAlgorithmOid != null) ? keyAlgorithmOid : PKCSObjectIdentifiers.rsaEncryption,
      DERNull.INSTANCE);
}
 
Example #23
Source File: TlsHelper.java    From nifi with Apache License 2.0 5 votes vote down vote up
public static JcaPKCS10CertificationRequest generateCertificationRequest(String requestedDn, List<String> domainAlternativeNames,
                                                                         KeyPair keyPair, String signingAlgorithm) throws OperatorCreationException {
    JcaPKCS10CertificationRequestBuilder jcaPKCS10CertificationRequestBuilder = new JcaPKCS10CertificationRequestBuilder(new X500Name(requestedDn), keyPair.getPublic());

    // add Subject Alternative Name(s)
    try {
        jcaPKCS10CertificationRequestBuilder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, createDomainAlternativeNamesExtensions(domainAlternativeNames, requestedDn));
    } catch (IOException e) {
        throw new OperatorCreationException("Error while adding " + domainAlternativeNames + " as Subject Alternative Name.", e);
    }

    JcaContentSignerBuilder jcaContentSignerBuilder = new JcaContentSignerBuilder(signingAlgorithm);
    return new JcaPKCS10CertificationRequest(jcaPKCS10CertificationRequestBuilder.build(jcaContentSignerBuilder.build(keyPair.getPrivate())));
}
 
Example #24
Source File: CAdESSignature.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public List<eu.europa.esig.dss.validation.CommitmentTypeIndication> getCommitmentTypeIndications() {
	final Attribute commitmentTypeIndicationAttribute = getSignedAttribute(PKCSObjectIdentifiers.id_aa_ets_commitmentType);
	if (commitmentTypeIndicationAttribute == null) {
		return null;
	}

	try {
		List<eu.europa.esig.dss.validation.CommitmentTypeIndication> commitmentTypeIndications = null;
		final ASN1Set attrValues = commitmentTypeIndicationAttribute.getAttrValues();
		final int size = attrValues.size();
		if (size > 0) {
			commitmentTypeIndications = new ArrayList<>();
			for (int ii = 0; ii < size; ii++) {
				if (attrValues.getObjectAt(ii) instanceof ASN1Sequence) {
					final ASN1Sequence sequence = (ASN1Sequence) attrValues.getObjectAt(ii);
					final CommitmentTypeIndication commitmentTypeIndication = CommitmentTypeIndication.getInstance(sequence);
					final ASN1ObjectIdentifier commitmentTypeId = commitmentTypeIndication.getCommitmentTypeId();
					commitmentTypeIndications.add(new eu.europa.esig.dss.validation.CommitmentTypeIndication(commitmentTypeId.getId()));
				} else {
					LOG.warn("Unsupported type for CommitmentType : {}", attrValues.getObjectAt(ii).getClass());
				}
			}
		}
		return commitmentTypeIndications;
	} catch (Exception e) {
		throw new DSSException("Error when dealing with CommitmentTypeIndication!", e);
	}
}
 
Example #25
Source File: CAdESSignature.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public Date getSigningTime() {
	final Attribute attr = getSignedAttribute(PKCSObjectIdentifiers.pkcs_9_at_signingTime);
	if (attr == null) {
		return null;
	}
	final ASN1Set attrValues = attr.getAttrValues();
	final ASN1Encodable attrValue = attrValues.getObjectAt(0);
	final Date signingDate = DSSASN1Utils.getDate(attrValue);
	if (signingDate != null) {
		/*
		 * RFC 3852 [4] states that "dates between January 1, 1950 and
		 * December 31, 2049 (inclusive) must be encoded as UTCTime. Any
		 * dates with year values before 1950 or after 2049 must be encoded
		 * as GeneralizedTime".
		 */
		if (signingDate.compareTo(JANUARY_1950) >= 0 && signingDate.before(JANUARY_2050)) {
			// must be ASN1UTCTime
			if (!(attrValue instanceof ASN1UTCTime)) {
				LOG.error(
						"RFC 3852 states that dates between January 1, 1950 and December 31, 2049 (inclusive) must be encoded as UTCTime. Any dates with year values before 1950 or after 2049 must be encoded as GeneralizedTime. Date found is {} encoded as {}",
						signingDate, attrValue.getClass());
				return null;
			}
		}
		return signingDate;
	}
	if (LOG.isErrorEnabled()) {
		LOG.error("Error when reading signing time. Unrecognized {}", attrValue.getClass());
	}
	return null;
}
 
Example #26
Source File: X509Utils.java    From acme-client with Apache License 2.0 5 votes vote down vote up
public static PKCS10CertificationRequest generateCSR(String[] commonNames, KeyPair pair) throws OperatorCreationException, IOException {
	X500NameBuilder namebuilder = new X500NameBuilder(X500Name.getDefaultStyle());
	namebuilder.addRDN(BCStyle.CN, commonNames[0]);
	
	List<GeneralName> subjectAltNames = new ArrayList<>(commonNames.length);
	for (String cn:commonNames)
		subjectAltNames.add(new GeneralName(GeneralName.dNSName, cn));
	GeneralNames subjectAltName = new GeneralNames(subjectAltNames.toArray(new GeneralName[0]));         
	
	ExtensionsGenerator extGen = new ExtensionsGenerator();
	extGen.addExtension(Extension.subjectAlternativeName, false, subjectAltName.toASN1Primitive());
	
	PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(namebuilder.build(), pair.getPublic());
	p10Builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extGen.generate());
	JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder("SHA256withRSA");
	ContentSigner signer = csBuilder.build(pair.getPrivate());
	PKCS10CertificationRequest request = p10Builder.build(signer);
	return request;
}
 
Example #27
Source File: MyUtil.java    From xipki with Apache License 2.0 5 votes vote down vote up
public static PKCS10CertificationRequest generateRequest(PrivateKey privatekey,
    SubjectPublicKeyInfo subjectPublicKeyInfo, X500Name subjectDn,
    String challengePassword, List<Extension> extensions)
    throws OperatorCreationException {
  Args.notNull(privatekey, "privatekey");
  Args.notNull(subjectPublicKeyInfo, "subjectPublicKeyInfo");
  Args.notNull(subjectDn, "subjectDn");

  Map<ASN1ObjectIdentifier, ASN1Encodable> attributes =
      new HashMap<ASN1ObjectIdentifier, ASN1Encodable>();

  if (StringUtil.isNotBlank(challengePassword)) {
    DERPrintableString asn1Pwd = new DERPrintableString(challengePassword);
    attributes.put(PKCSObjectIdentifiers.pkcs_9_at_challengePassword, asn1Pwd);
  }

  if (CollectionUtil.isNotEmpty(extensions)) {
    Extensions asn1Extensions = new Extensions(extensions.toArray(new Extension[0]));
    attributes.put(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, asn1Extensions);
  }

  PKCS10CertificationRequestBuilder csrBuilder =
      new PKCS10CertificationRequestBuilder(subjectDn, subjectPublicKeyInfo);

  if (attributes != null) {
    for (ASN1ObjectIdentifier attrType : attributes.keySet()) {
      csrBuilder.addAttribute(attrType, attributes.get(attrType));
    }
  }

  ContentSigner contentSigner = new JcaContentSignerBuilder(
      ScepUtil.getSignatureAlgorithm(privatekey, HashAlgo.SHA1)).build(privatekey);
  return csrBuilder.build(contentSigner);
}
 
Example #28
Source File: ScepUtil.java    From xipki with Apache License 2.0 5 votes vote down vote up
public static ASN1ObjectIdentifier extractDigesetAlgorithmIdentifier(String sigOid,
    byte[] sigParams) throws NoSuchAlgorithmException {
  Args.notBlank(sigOid, "sigOid");

  ASN1ObjectIdentifier algOid = new ASN1ObjectIdentifier(sigOid);

  ASN1ObjectIdentifier digestAlgOid;
  if (PKCSObjectIdentifiers.md5WithRSAEncryption.equals(algOid)) {
    digestAlgOid = PKCSObjectIdentifiers.md5;
  } else if (PKCSObjectIdentifiers.sha1WithRSAEncryption.equals(algOid)) {
    digestAlgOid = X509ObjectIdentifiers.id_SHA1;
  } else if (PKCSObjectIdentifiers.sha224WithRSAEncryption.equals(algOid)) {
    digestAlgOid = NISTObjectIdentifiers.id_sha224;
  } else if (PKCSObjectIdentifiers.sha256WithRSAEncryption.equals(algOid)) {
    digestAlgOid = NISTObjectIdentifiers.id_sha256;
  } else if (PKCSObjectIdentifiers.sha384WithRSAEncryption.equals(algOid)) {
    digestAlgOid = NISTObjectIdentifiers.id_sha384;
  } else if (PKCSObjectIdentifiers.sha512WithRSAEncryption.equals(algOid)) {
    digestAlgOid = NISTObjectIdentifiers.id_sha512;
  } else if (PKCSObjectIdentifiers.id_RSASSA_PSS.equals(algOid)) {
    RSASSAPSSparams param = RSASSAPSSparams.getInstance(sigParams);
    digestAlgOid = param.getHashAlgorithm().getAlgorithm();
  } else {
    throw new NoSuchAlgorithmException("unknown signature algorithm" + algOid.getId());
  }

  return digestAlgOid;
}
 
Example #29
Source File: DummyCertificate.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] getExtensionValue(String oid) {
    if (oid.equals(PKCSObjectIdentifiers.pkcs_9_at_challengePassword.toString())) {
        return EXT.getBytes();
    } else {
        return new byte[0];
    }
}
 
Example #30
Source File: CAdESSignature.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public byte[] getMessageDigestValue() {
	final Attribute messageDigestAttribute = getSignedAttribute(PKCSObjectIdentifiers.pkcs_9_at_messageDigest);
	if (messageDigestAttribute == null) {
		return null;
	}
	final ASN1OctetString asn1OctetString = (ASN1OctetString) messageDigestAttribute.getAttrValues().getObjectAt(0);
	return asn1OctetString.getOctets();
}