org.bouncycastle.asn1.DEROctetString Java Examples

The following examples show how to use org.bouncycastle.asn1.DEROctetString. 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: AttestationApplicationId.java    From android-key-attestation with Apache License 2.0 6 votes vote down vote up
private AttestationApplicationId(DEROctetString attestationApplicationId) throws IOException {
  ASN1Sequence attestationApplicationIdSequence =
      (ASN1Sequence) ASN1Sequence.fromByteArray(attestationApplicationId.getOctets());
  ASN1Set attestationPackageInfos =
      (ASN1Set)
          attestationApplicationIdSequence.getObjectAt(
              ATTESTATION_APPLICATION_ID_PACKAGE_INFOS_INDEX);
  this.packageInfos = new ArrayList<>();
  for (ASN1Encodable packageInfo : attestationPackageInfos) {
    this.packageInfos.add(new AttestationPackageInfo((ASN1Sequence) packageInfo));
  }

  ASN1Set digests =
      (ASN1Set)
          attestationApplicationIdSequence.getObjectAt(
              ATTESTATION_APPLICATION_ID_SIGNATURE_DIGESTS_INDEX);
  this.signatureDigests = new ArrayList<>();
  for (ASN1Encodable digest : digests) {
    this.signatureDigests.add(((ASN1OctetString) digest).getOctets());
  }
}
 
Example #2
Source File: ProxyP11Identity.java    From xipki with Apache License 2.0 6 votes vote down vote up
@Override
protected byte[] digestSecretKey0(long mechanism) throws P11TokenException {
  ProxyMessage.DigestSecretKeyTemplate template =
      new ProxyMessage.DigestSecretKeyTemplate(
          ((ProxyP11Slot) slot).getAsn1SlotId(), asn1KeyId, mechanism);
  byte[] result = ((ProxyP11Slot) slot).getModule().send(
      P11ProxyConstants.ACTION_DIGEST_SECRETKEY, template);

  ASN1OctetString octetString;
  try {
    octetString = DEROctetString.getInstance(result);
  } catch (IllegalArgumentException ex) {
    throw new P11TokenException("the returned result is not OCTET STRING");
  }

  return (octetString == null) ? null : octetString.getOctets();
}
 
Example #3
Source File: OcspRequestBuilder.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
/**
 * ATTENTION: The returned {@link OCSPReq} is not re-usable/cacheable! It contains a one-time nonce
 * and CA's will (should) reject subsequent requests that have the same nonce value.
 */
public OCSPReq build() throws OCSPException, IOException, CertificateEncodingException {
    SecureRandom generator = checkNotNull(this.generator, "generator");
    DigestCalculator calculator = checkNotNull(this.calculator, "calculator");
    X509Certificate certificate = checkNotNull(this.certificate, "certificate");
    X509Certificate issuer = checkNotNull(this.issuer, "issuer");

    BigInteger serial = certificate.getSerialNumber();

    CertificateID certId = new CertificateID(calculator,
            new X509CertificateHolder(issuer.getEncoded()), serial);

    OCSPReqBuilder builder = new OCSPReqBuilder();
    builder.addRequest(certId);

    byte[] nonce = new byte[8];
    generator.nextBytes(nonce);

    Extension[] extensions = new Extension[] {
            new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false,
                    new DEROctetString(nonce)) };

    builder.setRequestExtensions(new Extensions(extensions));

    return builder.build();
}
 
Example #4
Source File: ProxyMessage.java    From xipki with Apache License 2.0 6 votes vote down vote up
@Override
public ASN1Primitive toASN1Primitive() {
  ASN1EncodableVector vector = new ASN1EncodableVector();
  vector.add(new DERUTF8String(control.getLabel()));

  byte[] id = control.getId();
  if (id != null) {
    vector.add(new DERTaggedObject(0, new DEROctetString(id)));
  }

  Set<P11KeyUsage> usages = control.getUsages();
  if (CollectionUtil.isNotEmpty(usages)) {
    ASN1EncodableVector asn1Usages = new ASN1EncodableVector();
    for (P11KeyUsage usage : usages) {
      int value = usageToValueMap.get(usage);
      asn1Usages.add(new ASN1Enumerated(value));
    }
    vector.add(new DERTaggedObject(1, new DERSequence(asn1Usages)));
  }

  if (control.getExtractable() != null) {
    vector.add(new DERTaggedObject(2, ASN1Boolean.getInstance(control.getExtractable())));
  }

  return new DERSequence(vector);
}
 
Example #5
Source File: CertificateSignRequest.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
private Extension getKeyUsageExtension() throws IOException {
  int keyUsageFlag = KeyUsage.keyAgreement;
  if(digitalEncryption){
    keyUsageFlag |= KeyUsage.keyEncipherment | KeyUsage.dataEncipherment;
  }
  if(digitalSignature) {
    keyUsageFlag |= KeyUsage.digitalSignature;
  }

  if (ca) {
    keyUsageFlag |= KeyUsage.keyCertSign | KeyUsage.cRLSign;
  }
  KeyUsage keyUsage = new KeyUsage(keyUsageFlag);
  return new Extension(Extension.keyUsage, true,
      new DEROctetString(keyUsage));
}
 
Example #6
Source File: PublicKeyInfo.java    From InflatableDonkey with MIT License 6 votes vote down vote up
public PublicKeyInfo(ASN1Primitive primitive) {
    ASN1Primitive app = DER.asApplicationSpecific(APPLICATION_TAG, primitive);

    DERIterator i = DER.asSequence(app);
    Map<Integer, ASN1Primitive> tagged = i.derTaggedObjects();

    service = DER.as(ASN1Integer.class, i)
            .getValue()
            .intValue();

    type = DER.as(ASN1Integer.class, i)
            .getValue()
            .intValue();

    key = DER.as(DEROctetString.class, i)
            .getOctets();

    signatureInfo = Optional.ofNullable(tagged.get(SIGNATURE_INFO))
            .map(SignatureInfo::new);

    signature = Optional.ofNullable(tagged.get(SIGNATURE))
            .map(Signature::new);

    extendedSignature = Optional.ofNullable(tagged.get(EXTENDED_SIGNATURE))
            .map(ObjectSignature::new);
}
 
Example #7
Source File: OcspClientBouncyCastle.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Generates an OCSP request using BouncyCastle.
 * @param issuerCert	certificate of the issues
 * @param serialNumber	serial number
 * @return	an OCSP request
 * @throws OCSPException
 * @throws IOException
 */
private static OCSPReq generateOCSPRequest(X509Certificate issuerCert, BigInteger serialNumber) throws OCSPException, IOException, OperatorException, CertificateEncodingException {
    //Add provider BC
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    
    JcaDigestCalculatorProviderBuilder digestCalculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder();
    DigestCalculatorProvider digestCalculatorProvider = digestCalculatorProviderBuilder.build();
    DigestCalculator digestCalculator = digestCalculatorProvider.get(CertificateID.HASH_SHA1);
    // Generate the id for the certificate we are looking for
    CertificateID id = new CertificateID(digestCalculator, new JcaX509CertificateHolder(issuerCert), serialNumber);
    
    // basic request generation with nonce
    OCSPReqBuilder gen = new OCSPReqBuilder();
    
    gen.addRequest(id);
    
    // create details for nonce extension
    Extension ext = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString(new DEROctetString(PdfEncryption.createDocumentId()).getEncoded()));
    gen.setRequestExtensions(new Extensions(new Extension[]{ext}));
    
    return gen.build();
}
 
Example #8
Source File: PdfPKCS7.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Verifies a signature using the sub-filter adbe.x509.rsa_sha1.
 * @param contentsKey the /Contents key
 * @param certsKey the /Cert key
 * @param provider the provider or <code>null</code> for the default provider
 */    
public PdfPKCS7(byte[] contentsKey, byte[] certsKey, String provider) {
    try {
        this.provider = provider;
        X509CertParser cr = new X509CertParser();
        cr.engineInit(new ByteArrayInputStream(certsKey));
        certs = cr.engineReadAll();
        signCerts = certs;
        signCert = (X509Certificate)certs.iterator().next();
        crls = new ArrayList();
        ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(contentsKey));
        digest = ((DEROctetString)in.readObject()).getOctets();
        if (provider == null)
            sig = Signature.getInstance("SHA1withRSA");
        else
            sig = Signature.getInstance("SHA1withRSA", provider);
        sig.initVerify(signCert.getPublicKey());
    }
    catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}
 
Example #9
Source File: CadesLevelBaselineLTATimestampExtractor.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * The field certificatesHashIndex is a sequence of octet strings. Each one
 * contains the hash value of one instance of CertificateChoices within
 * certificates field of the root SignedData. A hash value for every instance of
 * CertificateChoices, as present at the time when the corresponding archive
 * time-stamp is requested, shall be included in certificatesHashIndex. No other
 * hash value shall be included in this field.
 *
 * @return
 * @throws eu.europa.esig.dss.model.DSSException
 */
private ASN1Sequence getCertificatesHashIndex() {

	final ASN1EncodableVector certificatesHashIndexVector = new ASN1EncodableVector();

	final Collection<CertificateToken> certificateTokens = certificates;
	for (final CertificateToken certificateToken : certificateTokens) {
		final byte[] digest = certificateToken.getDigest(hashIndexDigestAlgorithm);
		if (LOG.isDebugEnabled()) {
			LOG.debug("Adding to CertificatesHashIndex DSS-Identifier: {} with hash {}", certificateToken.getDSSId(), Utils.toHex(digest));
		}
		final DEROctetString derOctetStringDigest = new DEROctetString(digest);
		certificatesHashIndexVector.add(derOctetStringDigest);
	}
	return new DERSequence(certificatesHashIndexVector);
}
 
Example #10
Source File: OnlineOCSPSource.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
private BigInteger getEmbeddedNonceValue(final OCSPResp ocspResp) {
	try {
		BasicOCSPResp basicOCSPResp = (BasicOCSPResp)ocspResp.getResponseObject();
		
		Extension extension = basicOCSPResp.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce);
		ASN1OctetString extnValue = extension.getExtnValue();
		ASN1Primitive value;
		try {
			value = ASN1Primitive.fromByteArray(extnValue.getOctets());
		} catch (IOException ex) {
			throw new OCSPException("Invalid encoding of nonce extension value in OCSP response", ex);
		}
		if (value instanceof DEROctetString) {
			return new BigInteger(((DEROctetString) value).getOctets());
		}
		throw new OCSPException("Nonce extension value in OCSP response is not an OCTET STRING");
	} catch (Exception e) {
		throw new DSSException(String.format("Unable to extract the nonce from the OCSPResponse! Reason : [%s]", e.getMessage()), e);
	}
}
 
Example #11
Source File: SECPrivateKey.java    From InflatableDonkey with MIT License 6 votes vote down vote up
public SECPrivateKey(ASN1Primitive primitive) {
    DERIterator i = DER.asSequence(primitive);
    Map<Integer, ASN1Primitive> tagged = i.derTaggedObjects();

    version = DER.as(ASN1Integer.class, i)
            .getValue()
            .intValue();

    privateKey = DER.as(DEROctetString.class, i)
            .getOctets();

    parameters = Optional.ofNullable(tagged.get(PARAMETERS))
            .map(DER.as(DEROctetString.class))
            .map(ASN1OctetString::getOctets);

    publicKey = Optional.ofNullable(tagged.get(PUBLIC_KEY))
            .map(DER.as(DERBitString.class))
            .map(DERBitString::getBytes);
}
 
Example #12
Source File: BackupEscrow.java    From InflatableDonkey with MIT License 6 votes vote down vote up
public BackupEscrow(ASN1Primitive primitive) {
    ASN1Primitive app = DER.asApplicationSpecific(APPLICATION_TAG, primitive);
    DERIterator i = DER.asSequence(app);

    wrappedKey = DER.as(DEROctetString.class, i)
            .getOctets();

    data = DER.as(DEROctetString.class, i)
            .getOctets();

    x = DER.as(DEROctetString.class, i)
            .getOctets();

    y = DER.as(ASN1Integer.class, i)
            .getValue()
            .intValue();

    masterKeyPublic = DER.as(DEROctetString.class, i)
            .getOctets();
}
 
Example #13
Source File: CAdESTimestampSource.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
private List<TimestampedReference> getSignedDataRevocationReferences(final ASN1Sequence atsHashIndex, final DigestAlgorithm digestAlgorithm,
		final String timestampId) {
	List<TimestampedReference> references = new ArrayList<>();
	
	// get CRL references
	ASN1Sequence crlsHashIndex = DSSASN1Utils.getCRLHashIndex(atsHashIndex);
	List<DEROctetString> crlsHashList = DSSASN1Utils.getDEROctetStrings(crlsHashIndex);
	if (signatureCRLSource instanceof CMSCRLSource) {
		CMSCRLSource cmsCRLSource = (CMSCRLSource) signatureCRLSource;
		for (EncapsulatedRevocationTokenIdentifier token : cmsCRLSource.getCMSSignedDataRevocationBinaries()) {
			if (isDigestValuePresent(token.getDigestValue(digestAlgorithm), crlsHashList)) {
				addReference(references, token, TimestampedObjectType.REVOCATION);
			} else {
				LOG.warn("The CRL Token with id [{}] was not included to the message imprint of timestamp with id [{}] "
						+ "or was added to the CMS SignedData after this ArchiveTimestamp!", 
						token.asXmlId(), timestampId);
			}
		}
	}

	// get OCSP references
	List<TimestampedReference> ocspReferences = getSignedDataOCSPReferences(crlsHashList, digestAlgorithm, timestampId);
	references.addAll(ocspReferences);
	
	return references;
}
 
Example #14
Source File: KerberosRelevantAuthData.java    From jcifs-ng with GNU Lesser General Public License v2.1 6 votes vote down vote up
public KerberosRelevantAuthData ( byte[] token, Map<Integer, KerberosKey> keys ) throws PACDecodingException {
    DLSequence authSequence;
    try {
        try ( ASN1InputStream stream = new ASN1InputStream(new ByteArrayInputStream(token)) ) {
            authSequence = ASN1Util.as(DLSequence.class, stream);
        }
    }
    catch ( IOException e ) {
        throw new PACDecodingException("Malformed kerberos ticket", e);
    }

    this.authorizations = new ArrayList<>();
    Enumeration<?> authElements = authSequence.getObjects();
    while ( authElements.hasMoreElements() ) {
        DLSequence authElement = ASN1Util.as(DLSequence.class, authElements);
        ASN1Integer authType = ASN1Util.as(ASN1Integer.class, ASN1Util.as(DERTaggedObject.class, authElement, 0));
        DEROctetString authData = ASN1Util.as(DEROctetString.class, ASN1Util.as(DERTaggedObject.class, authElement, 1));

        this.authorizations.addAll(KerberosAuthData.parse(authType.getValue().intValue(), authData.getOctets(), keys));
    }
}
 
Example #15
Source File: SubjectAlternativeName.java    From vespa with Apache License 2.0 6 votes vote down vote up
private String getValue(GeneralName bcGeneralName) {
    ASN1Encodable name = bcGeneralName.getName();
    switch (bcGeneralName.getTagNo()) {
        case GeneralName.rfc822Name:
        case GeneralName.dNSName:
        case GeneralName.uniformResourceIdentifier:
            return DERIA5String.getInstance(name).getString();
        case GeneralName.directoryName:
            return X500Name.getInstance(name).toString();
        case GeneralName.iPAddress:
            byte[] octets = DEROctetString.getInstance(name.toASN1Primitive()).getOctets();
            try {
                return InetAddress.getByAddress(octets).getHostAddress();
            } catch (UnknownHostException e) {
                // Only thrown if IP address is of invalid length, which is an illegal argument
                throw new IllegalArgumentException(e);
            }
        default:
            return name.toString();
    }
}
 
Example #16
Source File: XijsonCertprofile.java    From xipki with Apache License 2.0 6 votes vote down vote up
private void initAuthorizationTemplate(Set<ASN1ObjectIdentifier> extnIds,
    Map<String, ExtensionType> extensions) throws CertprofileException {
  ASN1ObjectIdentifier type = ObjectIdentifiers.Xipki.id_xipki_ext_authorizationTemplate;
  if (extensionControls.containsKey(type)) {
    extnIds.remove(type);
    AuthorizationTemplate extConf = getExtension(type, extensions).getAuthorizationTemplate();
    if (extConf != null) {
      ASN1EncodableVector vec = new ASN1EncodableVector();
      vec.add(new ASN1ObjectIdentifier(extConf.getType().getOid()));
      vec.add(new DEROctetString(extConf.getAccessRights().getValue()));
      ASN1Encodable extValue = new DERSequence(vec);
      authorizationTemplate =
          new ExtensionValue(extensionControls.get(type).isCritical(), extValue);
    }
  }
}
 
Example #17
Source File: PdfPublicKeySecurityHandler.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
private KeyTransRecipientInfo computeRecipientInfo(X509Certificate x509certificate, byte[] abyte0)
    throws GeneralSecurityException, IOException
{
    ASN1InputStream asn1inputstream = 
        new ASN1InputStream(new ByteArrayInputStream(x509certificate.getTBSCertificate()));
    TBSCertificateStructure tbscertificatestructure = 
        TBSCertificateStructure.getInstance(asn1inputstream.readObject());
    AlgorithmIdentifier algorithmidentifier = tbscertificatestructure.getSubjectPublicKeyInfo().getAlgorithm();
    IssuerAndSerialNumber issuerandserialnumber = 
        new IssuerAndSerialNumber(
            tbscertificatestructure.getIssuer(), 
            tbscertificatestructure.getSerialNumber().getValue());
    Cipher cipher = Cipher.getInstance(algorithmidentifier.getAlgorithm().getId());        
    cipher.init(1, x509certificate);
    DEROctetString deroctetstring = new DEROctetString(cipher.doFinal(abyte0));
    RecipientIdentifier recipId = new RecipientIdentifier(issuerandserialnumber);
    return new KeyTransRecipientInfo( recipId, algorithmidentifier, deroctetstring);
}
 
Example #18
Source File: CAdESLevelBaselineB.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void addSignaturePolicyId(final CAdESSignatureParameters parameters, final ASN1EncodableVector signedAttributes) {

		Policy policy = parameters.bLevel().getSignaturePolicy();
		if (policy != null) {

			final String policyId = policy.getId();
			SignaturePolicyIdentifier sigPolicy = null;

			if (Utils.isStringEmpty(policyId)) {// implicit
				sigPolicy = new SignaturePolicyIdentifier();
			} else { // explicit
				final ASN1ObjectIdentifier derOIPolicyId = new ASN1ObjectIdentifier(policyId);
				final ASN1ObjectIdentifier oid = new ASN1ObjectIdentifier(policy.getDigestAlgorithm().getOid());
				final AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(oid);
				OtherHashAlgAndValue otherHashAlgAndValue = new OtherHashAlgAndValue(algorithmIdentifier, new DEROctetString(policy.getDigestValue()));

				if (Utils.isStringNotEmpty(policy.getSpuri())) {
					SigPolicyQualifierInfo policyQualifierInfo = new SigPolicyQualifierInfo(PKCSObjectIdentifiers.id_spq_ets_uri,
							new DERIA5String(policy.getSpuri()));
					SigPolicyQualifierInfo[] qualifierInfos = new SigPolicyQualifierInfo[] { policyQualifierInfo };
					SigPolicyQualifiers qualifiers = new SigPolicyQualifiers(qualifierInfos);

					sigPolicy = new SignaturePolicyIdentifier(new SignaturePolicyId(derOIPolicyId, otherHashAlgAndValue, qualifiers));
				} else {
					sigPolicy = new SignaturePolicyIdentifier(new SignaturePolicyId(derOIPolicyId, otherHashAlgAndValue));
				}
			}

			final DERSet attrValues = new DERSet(sigPolicy);
			final Attribute attribute = new Attribute(id_aa_ets_sigPolicyId, attrValues);
			signedAttributes.add(attribute);
		}
	}
 
Example #19
Source File: CAdESAttribute.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Returns a list of {@link ASN1Primitive} values found in the attribute
 * @return list of {@link ASN1Primitive}
 */
private List<ASN1Primitive> getASN1Primitives() {
	final List<ASN1Primitive> primitives = new ArrayList<>();
	final ASN1Set attrValues = attribute.getAttrValues();
	for (final ASN1Encodable value : attrValues.toArray()) {
		if (value instanceof DEROctetString) {
			LOG.warn("Illegal content for timestamp (OID : {}) : OCTET STRING is not allowed !", this);
		} else {
			primitives.add(value.toASN1Primitive());
		}
	}
	return primitives;
}
 
Example #20
Source File: DSSASN1Utils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Returns list of {@code DEROctetString} from an {@code ASN1Sequence}
 * Useful when needed to get a list of hash values
 * 
 * @param asn1Sequence {@link ASN1Sequence} to get list from
 * @return list of {@link DEROctetString}s
 */
@SuppressWarnings("unchecked")
public static List<DEROctetString> getDEROctetStrings(final ASN1Sequence asn1Sequence) {
	final List<DEROctetString> derOctetStrings = new ArrayList<>();
	if (asn1Sequence != null) {
		derOctetStrings.addAll(Collections.list(asn1Sequence.getObjects()));
	}
	return derOctetStrings;
}
 
Example #21
Source File: KeyStoreTableModel.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
private String getCertificateSKI(String alias, KeyStore keyStore) throws CryptoException, KeyStoreException {
	X509Certificate x509Cert = getCertificate(alias, keyStore);
	try {
		byte[] skiValue = x509Cert.getExtensionValue(Extension.subjectKeyIdentifier.getId());
		byte[] octets = DEROctetString.getInstance(skiValue).getOctets();
		byte[] skiBytes = SubjectKeyIdentifier.getInstance(octets).getKeyIdentifier();
		return HexUtil.getHexString(skiBytes);
	} catch (Exception e) {
		return "-";
	}
}
 
Example #22
Source File: BCECUtil.java    From jiguang-java-client-common with MIT License 5 votes vote down vote up
/**
 * 将SEC1标准的私钥字节流恢复为PKCS8标准的字节流
 *
 * @param sec1Key
 * @return
 * @throws IOException
 */
public static byte[] convertECPrivateKeySEC1ToPKCS8(byte[] sec1Key) throws IOException {
    /**
     * 参考org.bouncycastle.asn1.pkcs.PrivateKeyInfo和
     * org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey,逆向拼装
     */
    X962Parameters params = getDomainParametersFromName(SM2Util.JDK_EC_SPEC, false);
    ASN1OctetString privKey = new DEROctetString(sec1Key);
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(new ASN1Integer(0)); //版本号
    v.add(new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, params)); //算法标识
    v.add(privKey);
    DERSequence ds = new DERSequence(v);
    return ds.getEncoded(ASN1Encoding.DER);
}
 
Example #23
Source File: KeySet.java    From InflatableDonkey with MIT License 5 votes vote down vote up
public KeySet(ASN1Primitive primitive) {

        ASN1Primitive app = DER.asApplicationSpecific(APPLICATION_TAG, primitive);
        DERIterator i = DER.asSequence(app);

        name = DER.as(DERUTF8String.class, i)
                .getString();

        keys = DER.asSet(i, PrivateKey::new);

        serviceKeyIDs = DER.asSet(i, TypeData::new);

        Optional<byte[]> optionalChecksum = i.nextIf(DEROctetString.class)
                .map(ASN1OctetString::getOctets);

        flags = i.nextIf(ASN1Integer.class)
                .map(ASN1Integer::getValue)
                .map(BigInteger::intValue);

        signatureInfo = i.optional()
                .map(SignatureInfo::new);

        checksum = calculateChecksum();

        Optional<Boolean> match = optionalChecksum.map(c -> Arrays.equals(c, checksum));

        if (match.isPresent()) {
            if (match.get()) {
                logger.debug("** KeySet() - checksums match");
            } else {
                try {
                    logger.debug("** KeySet()  - checksums do not match in: {} constructed: {}",
                            Hex.toHexString(primitive.getEncoded()),
                            Hex.toHexString(toASN1Primitive(false).getEncoded()));
                } catch (IOException ex) {
                    logger.debug("** KeySet() - IOException: ", ex);
                }
            }
        }
    }
 
Example #24
Source File: DSSASN1Utils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Indicates if the revocation data should be checked for an OCSP signing certificate.<br>
 * http://www.ietf.org/rfc/rfc2560.txt?number=2560<br>
 * A CA may specify that an OCSP client can trust a responder for the lifetime of the responder's certificate. The
 * CA does so by including the extension id-pkix-ocsp-nocheck. This SHOULD be a non-critical extension. The value of
 * the extension should be NULL.
 *
 * @param token
 *            the certificate to be checked
 * @return true if the certificate has the id_pkix_ocsp_nocheck extension
 */
public static boolean hasIdPkixOcspNoCheckExtension(CertificateToken token) {
	final byte[] extensionValue = token.getCertificate().getExtensionValue(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck.getId());
	if (extensionValue != null) {
		try {
			final ASN1Primitive derObject = toASN1Primitive(extensionValue);
			if (derObject instanceof DEROctetString) {
				return isDEROctetStringNull((DEROctetString) derObject);
			}
		} catch (Exception e) {
			LOG.debug("Exception when processing 'id_pkix_ocsp_no_check'", e);
		}
	}
	return false;
}
 
Example #25
Source File: PkiMessage.java    From xipki with Apache License 2.0 5 votes vote down vote up
private AttributeTable getSignedAttributes() {
  ASN1EncodableVector vec = new ASN1EncodableVector();
  // messageType
  addAttribute(vec, ScepObjectIdentifiers.ID_MESSAGE_TYPE,
      new DERPrintableString(Integer.toString(messageType.getCode())));

  // senderNonce
  addAttribute(vec, ScepObjectIdentifiers.ID_SENDER_NONCE,
      new DEROctetString(senderNonce.getBytes()));

  // transactionID
  addAttribute(vec, ScepObjectIdentifiers.ID_TRANSACTION_ID,
      new DERPrintableString(transactionId.getId()));

  // failInfo
  if (failInfo != null) {
    addAttribute(vec, ScepObjectIdentifiers.ID_FAILINFO,
        new DERPrintableString(Integer.toString(failInfo.getCode())));
  }

  // pkiStatus
  if (pkiStatus != null) {
    addAttribute(vec, ScepObjectIdentifiers.ID_PKI_STATUS,
        new DERPrintableString(Integer.toString(pkiStatus.getCode())));
  }

  // recipientNonce
  if (recipientNonce != null) {
    addAttribute(vec, ScepObjectIdentifiers.ID_RECIPIENT_NONCE,
        new DEROctetString(recipientNonce.getBytes()));
  }

  for (ASN1ObjectIdentifier type : signedAttributes.keySet()) {
    addAttribute(vec, type, signedAttributes.get(type));
  }
  return new AttributeTable(vec);
}
 
Example #26
Source File: NegTokenTarg.java    From jcifs-ng with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public byte[] toByteArray () {
    try {
        ByteArrayOutputStream collector = new ByteArrayOutputStream();
        DEROutputStream der = new DEROutputStream(collector);
        ASN1EncodableVector fields = new ASN1EncodableVector();
        int res = getResult();
        if ( res != UNSPECIFIED_RESULT ) {
            fields.add(new DERTaggedObject(true, 0, new ASN1Enumerated(res)));
        }
        ASN1ObjectIdentifier mech = getMechanism();
        if ( mech != null ) {
            fields.add(new DERTaggedObject(true, 1, mech));
        }
        byte[] mechanismToken = getMechanismToken();
        if ( mechanismToken != null ) {
            fields.add(new DERTaggedObject(true, 2, new DEROctetString(mechanismToken)));
        }
        byte[] mechanismListMIC = getMechanismListMIC();
        if ( mechanismListMIC != null ) {
            fields.add(new DERTaggedObject(true, 3, new DEROctetString(mechanismListMIC)));
        }
        der.writeObject(new DERTaggedObject(true, 1, new DERSequence(fields)));
        return collector.toByteArray();
    }
    catch ( IOException ex ) {
        throw new IllegalStateException(ex.getMessage());
    }
}
 
Example #27
Source File: NegTokenInit.java    From jcifs-ng with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public byte[] toByteArray () {
    try {
        ASN1EncodableVector fields = new ASN1EncodableVector();
        ASN1ObjectIdentifier[] mechs = getMechanisms();
        if ( mechs != null ) {
            ASN1EncodableVector vector = new ASN1EncodableVector();
            for ( int i = 0; i < mechs.length; i++ ) {
                vector.add(mechs[ i ]);
            }
            fields.add(new DERTaggedObject(true, 0, new DERSequence(vector)));
        }
        int ctxFlags = getContextFlags();
        if ( ctxFlags != 0 ) {
            fields.add(new DERTaggedObject(true, 1, new DERBitString(ctxFlags)));
        }
        byte[] mechanismToken = getMechanismToken();
        if ( mechanismToken != null ) {
            fields.add(new DERTaggedObject(true, 2, new DEROctetString(mechanismToken)));
        }
        byte[] mechanismListMIC = getMechanismListMIC();
        if ( mechanismListMIC != null ) {
            fields.add(new DERTaggedObject(true, 3, new DEROctetString(mechanismListMIC)));
        }

        ASN1EncodableVector ev = new ASN1EncodableVector();
        ev.add(SPNEGO_OID);
        ev.add(new DERTaggedObject(true, 0, new DERSequence(fields)));
        ByteArrayOutputStream collector = new ByteArrayOutputStream();
        DEROutputStream der = new DEROutputStream(collector);
        DERApplicationSpecific derApplicationSpecific = new DERApplicationSpecific(0, ev);
        der.writeObject(derApplicationSpecific);
        return collector.toByteArray();
    }
    catch ( IOException ex ) {
        throw new IllegalStateException(ex.getMessage());
    }
}
 
Example #28
Source File: AttestationApplicationIdTest.java    From android-key-attestation with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateEmptyAttestationApplicationIdFromEmptyOrInvalidInput() {
  assertThat(AttestationApplicationId.createAttestationApplicationId(null)).isNull();
  assertThat(
          AttestationApplicationId.createAttestationApplicationId(
              new DEROctetString("Invalid DEROctet String".getBytes(UTF_8))))
      .isNull();
}
 
Example #29
Source File: DSSRevocationUtils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Convert a BasicOCSPResp in OCSPResp (connection status is set to
 * SUCCESSFUL).
 *
 * @param basicOCSPRespBinary
 *            the binary of BasicOCSPResp
 * @return an instance of OCSPResp
 */
public static OCSPResp fromBasicToResp(final byte[] basicOCSPRespBinary) {
	final OCSPResponseStatus responseStatus = new OCSPResponseStatus(OCSPResponseStatus.SUCCESSFUL);
	final DEROctetString derBasicOCSPResp = new DEROctetString(basicOCSPRespBinary);
	final ResponseBytes responseBytes = new ResponseBytes(OCSPObjectIdentifiers.id_pkix_ocsp_basic, derBasicOCSPResp);
	final OCSPResponse ocspResponse = new OCSPResponse(responseStatus, responseBytes);
	// !!! todo to be checked: System.out.println("===> RECREATED: " +
	// ocspResp.hashCode());
	return new OCSPResp(ocspResponse);
}
 
Example #30
Source File: ProxyP11Identity.java    From xipki with Apache License 2.0 5 votes vote down vote up
@Override
protected byte[] sign0(long mechanism, P11Params parameters, byte[] content)
    throws P11TokenException {
  ProxyMessage.P11Params p11Param = null;
  if (parameters != null) {
    if (parameters instanceof P11RSAPkcsPssParams) {
      p11Param = new ProxyMessage.P11Params(ProxyMessage.P11Params.TAG_RSA_PKCS_PSS,
          new ProxyMessage.RSAPkcsPssParams((P11RSAPkcsPssParams) parameters));
    } else if (parameters instanceof P11ByteArrayParams) {
      byte[] bytes = ((P11ByteArrayParams) parameters).getBytes();
      p11Param = new ProxyMessage.P11Params(ProxyMessage.P11Params.TAG_OPAQUE,
          new DEROctetString(bytes));
    } else if (parameters instanceof P11IVParams) {
      p11Param = new ProxyMessage.P11Params(ProxyMessage.P11Params.TAG_IV,
          new DEROctetString(((P11IVParams) parameters).getIV()));
    } else {
      throw new IllegalArgumentException("unkown parameter 'parameters'");
    }
  }

  ProxyMessage.SignTemplate signTemplate = new ProxyMessage.SignTemplate(
      ((ProxyP11Slot) slot).getAsn1SlotId(), asn1KeyId, mechanism, p11Param, content);
  byte[] result = ((ProxyP11Slot) slot).getModule().send(P11ProxyConstants.ACTION_SIGN,
      signTemplate);

  ASN1OctetString octetString;
  try {
    octetString = DEROctetString.getInstance(result);
  } catch (IllegalArgumentException ex) {
    throw new P11TokenException("the returned result is not OCTET STRING");
  }

  return (octetString == null) ? null : octetString.getOctets();
}