Java Code Examples for org.bouncycastle.asn1.DEROctetString

The following examples show how to use org.bouncycastle.asn1.DEROctetString. 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
Source Project: hadoop-ozone   Source File: CertificateSignRequest.java    License: 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 2
Source Project: netty-4.1.22   Source File: OcspRequestBuilder.java    License: 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 3
Source Project: xipki   Source File: ProxyP11Identity.java    License: 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 4
/**
 * 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 5
Source Project: itext2   Source File: PdfPKCS7.java    License: 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 6
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 7
Source Project: InflatableDonkey   Source File: BackupEscrow.java    License: 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 8
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 9
Source Project: xipki   Source File: XijsonCertprofile.java    License: 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 10
Source Project: vespa   Source File: SubjectAlternativeName.java    License: 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 11
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 12
Source Project: InflatableDonkey   Source File: SECPrivateKey.java    License: 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 13
Source Project: dss   Source File: OnlineOCSPSource.java    License: 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 14
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 15
/**
 * 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 16
Source Project: InflatableDonkey   Source File: PublicKeyInfo.java    License: 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 17
Source Project: xipki   Source File: ProxyMessage.java    License: 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 18
Source Project: hadoop-ozone   Source File: CertificateSignRequest.java    License: Apache License 2.0 5 votes vote down vote up
private Optional<Extension> getSubjectAltNameExtension() throws
    IOException {
  if (altNames != null) {
    return Optional.of(new Extension(Extension.subjectAlternativeName,
        false, new DEROctetString(new GeneralNames(
        altNames.toArray(new GeneralName[altNames.size()])))));
  }
  return Optional.empty();
}
 
Example 19
Source Project: InflatableDonkey   Source File: TypeData.java    License: MIT License 5 votes vote down vote up
@Override
public ASN1Primitive toASN1Primitive() {
    ASN1EncodableVector vector = DER.vector(new ASN1Integer(type),
            new DEROctetString(data()));

    return new DERSequence(vector);
}
 
Example 20
Source Project: Auditor   Source File: Asn1Utils.java    License: MIT License 5 votes vote down vote up
public static byte[] getByteArrayFromAsn1(ASN1Encodable asn1Encodable)
        throws CertificateParsingException {
    if (asn1Encodable == null || !(asn1Encodable instanceof DEROctetString)) {
        throw new CertificateParsingException("Expected DEROctetString");
    }
    ASN1OctetString derOctectString = (ASN1OctetString) asn1Encodable;
    return derOctectString.getOctets();
}
 
Example 21
Source Project: InflatableDonkey   Source File: NOS.java    License: MIT License 5 votes vote down vote up
@Override
public ASN1Primitive toASN1Primitive() {

    ASN1EncodableVector vector = DER.vector(
            new ASN1Integer(x),
            y.map(ASN1Integer::new).orElse(null),
            new DEROctetString(key()));

    return new DERSequence(vector);
}
 
Example 22
Source Project: FairEmail   Source File: EmailService.java    License: GNU General Public License v3.0 5 votes vote down vote up
private static String getKeyId(X509Certificate certificate) {
    try {
        byte[] extension = certificate.getExtensionValue(Extension.subjectKeyIdentifier.getId());
        if (extension == null)
            return null;
        byte[] bytes = DEROctetString.getInstance(extension).getOctets();
        SubjectKeyIdentifier keyId = SubjectKeyIdentifier.getInstance(bytes);
        return Helper.hex(keyId.getKeyIdentifier());
    } catch (Throwable ex) {
        Log.e(ex);
        return null;
    }
}
 
Example 23
Source Project: gmhelper   Source File: BCECUtil.java    License: Apache License 2.0 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 24
Source Project: InflatableDonkey   Source File: Item.java    License: MIT License 5 votes vote down vote up
public Item(ASN1Primitive primitive) {
    DERIterator i = DER.asSequence(primitive);

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

    data = DER.as(DEROctetString.class, i)
            .getOctets();
}
 
Example 25
Source Project: gmhelper   Source File: SM2Util.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @param mode      指定密文结构,旧标准的为C1C2C3,新的[《SM2密码算法使用规范》 GM/T 0009-2012]标准为C1C3C2
 * @param derCipher 根据mode输入C1C2C3或C1C3C2顺序DER编码后的密文
 * @return 根据mode不同,输出的密文C1C2C3排列顺序不同。C1为65字节第1字节为压缩标识,这里固定为0x04,后面64字节为xy分量各32字节。C3为32字节。C2长度与原文一致。
 * @throws Exception
 */
public static byte[] decodeDERSM2Cipher(Mode mode, byte[] derCipher) throws Exception {
    ASN1Sequence as = DERSequence.getInstance(derCipher);
    byte[] c1x = ((ASN1Integer) as.getObjectAt(0)).getValue().toByteArray();
    byte[] c1y = ((ASN1Integer) as.getObjectAt(1)).getValue().toByteArray();
    byte[] c3;
    byte[] c2;
    if (mode == Mode.C1C2C3) {
        c2 = ((DEROctetString) as.getObjectAt(2)).getOctets();
        c3 = ((DEROctetString) as.getObjectAt(3)).getOctets();
    } else if (mode == Mode.C1C3C2) {
        c3 = ((DEROctetString) as.getObjectAt(2)).getOctets();
        c2 = ((DEROctetString) as.getObjectAt(3)).getOctets();
    } else {
        throw new Exception("Unsupported mode:" + mode);
    }

    int pos = 0;
    byte[] cipherText = new byte[1 + c1x.length + c1y.length + c2.length + c3.length];
    final byte uncompressedFlag = 0x04;
    cipherText[0] = uncompressedFlag;
    pos += 1;
    System.arraycopy(c1x, 0, cipherText, pos, c1x.length);
    pos += c1x.length;
    System.arraycopy(c1y, 0, cipherText, pos, c1y.length);
    pos += c1y.length;
    if (mode == Mode.C1C2C3) {
        System.arraycopy(c2, 0, cipherText, pos, c2.length);
        pos += c2.length;
        System.arraycopy(c3, 0, cipherText, pos, c3.length);
    } else if (mode == Mode.C1C3C2) {
        System.arraycopy(c3, 0, cipherText, pos, c3.length);
        pos += c3.length;
        System.arraycopy(c2, 0, cipherText, pos, c2.length);
    }
    return cipherText;
}
 
Example 26
Source Project: fabric-chaincode-java   Source File: ClientIdentity.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * parseAttributes returns a map of the attributes associated with an identity.
 *
 * @param extensionValue DER-encoded Octet string stored in the attributes
 *                       extension of the certificate, as a byte array
 * @return attrMap {Map<String, String>} a map of identity attributes as key
 *         value pair strings
 * @throws IOException
 */
private Map<String, String> parseAttributes(final byte[] extensionValue) throws IOException {

    final Map<String, String> attrMap = new HashMap<String, String>();

    // Create ASN1InputStream from extensionValue
    try (ByteArrayInputStream inStream = new ByteArrayInputStream(extensionValue); ASN1InputStream asn1InputStream = new ASN1InputStream(inStream)) {

        // Read the DER object
        final ASN1Primitive derObject = asn1InputStream.readObject();
        if (derObject instanceof DEROctetString) {
            final DEROctetString derOctetString = (DEROctetString) derObject;

            // Create attributeString from octets and create JSON object
            final String attributeString = new String(derOctetString.getOctets(), UTF_8);
            final JSONObject extJSON = new JSONObject(attributeString);
            final JSONObject attrs = extJSON.getJSONObject("attrs");

            final Iterator<String> keys = attrs.keys();
            while (keys.hasNext()) {
                final String key = keys.next();
                // Populate map with attributes and values
                attrMap.put(key, attrs.getString(key));
            }
        }
    } catch (final JSONException error) {
        // creating a JSON object failed
        // decoded extensionValue is not a string containing JSON
        logger.error(() -> logger.formatError(error));
        // return empty map
    }
    return attrMap;
}
 
Example 27
Source Project: portecle   Source File: X509Ext.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get Policy Constraints (2.5.29.36) extension value as a string.
 *
 * <pre>
 * PolicyConstraints ::= SEQUENCE {
 *     requireExplicitPolicy           [0] SkipCerts OPTIONAL,
 *     inhibitPolicyMapping            [1] SkipCerts OPTIONAL }
 * SkipCerts ::= INTEGER (0..MAX)
 * </pre>
 *
 * @param bValue The octet string value
 * @return Extension value as a string
 * @throws IOException If an I/O problem occurs
 */
private String getPolicyConstraintsStringValue(byte[] bValue)
    throws IOException
{
	// Get sequence of policy constraint
	ASN1Sequence policyConstraints = (ASN1Sequence) ASN1Primitive.fromByteArray(bValue);

	StringBuilder strBuff = new StringBuilder();

	for (int i = 0, len = policyConstraints.size(); i < len; i++)
	{
		DERTaggedObject policyConstraint = (DERTaggedObject) policyConstraints.getObjectAt(i);
		ASN1Integer skipCerts = new ASN1Integer(((DEROctetString) policyConstraint.getObject()).getOctets());
		int iSkipCerts = skipCerts.getValue().intValue();

		switch (policyConstraint.getTagNo())
		{
			case 0: // Require Explicit Policy Skip Certs
				if (strBuff.length() != 0)
				{
					strBuff.append("<br><br>");
				}
				strBuff.append(MessageFormat.format(RB.getString("RequireExplicitPolicy"), iSkipCerts));
				break;
			case 1: // Inhibit Policy Mapping Skip Certs
				if (strBuff.length() != 0)
				{
					strBuff.append("<br><br>");
				}
				strBuff.append(MessageFormat.format(RB.getString("InhibitPolicyMapping"), iSkipCerts));
				break;
		}
	}

	return strBuff.toString();

}
 
Example 28
Source Project: InflatableDonkey   Source File: PrivateKey.java    License: MIT License 5 votes vote down vote up
public PrivateKey(ASN1Primitive primitive) {
    DERIterator i = DER.asSequence(primitive);

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

    publicKeyInfo = i.optional()
            .map(PublicKeyInfo::new);
}
 
Example 29
Source Project: xipki   Source File: CmpAgent.java    License: Apache License 2.0 5 votes vote down vote up
private PKIMessage buildUnrevokeOrRemoveCertRequest(UnrevokeOrRemoveCertRequest request,
    int reasonCode) throws CmpClientException {
  PKIHeader header = buildPkiHeader(null);

  List<UnrevokeOrRemoveCertRequest.Entry> requestEntries = request.getRequestEntries();
  List<RevDetails> revDetailsArray = new ArrayList<>(requestEntries.size());
  for (UnrevokeOrRemoveCertRequest.Entry requestEntry : requestEntries) {
    CertTemplateBuilder certTempBuilder = new CertTemplateBuilder();
    certTempBuilder.setIssuer(requestEntry.getIssuer());
    certTempBuilder.setSerialNumber(new ASN1Integer(requestEntry.getSerialNumber()));
    byte[] aki = requestEntry.getAuthorityKeyIdentifier();
    if (aki != null) {
      Extensions certTempExts = getCertTempExtensions(aki);
      certTempBuilder.setExtensions(certTempExts);
    }

    Extension[] extensions = new Extension[1];

    try {
      ASN1Enumerated reason = new ASN1Enumerated(reasonCode);
      extensions[0] = new Extension(Extension.reasonCode, true,
              new DEROctetString(reason.getEncoded()));
    } catch (IOException ex) {
      throw new CmpClientException(ex.getMessage(), ex);
    }
    Extensions exts = new Extensions(extensions);

    RevDetails revDetails = new RevDetails(certTempBuilder.build(), exts);
    revDetailsArray.add(revDetails);
  }

  RevReqContent content = new RevReqContent(revDetailsArray.toArray(new RevDetails[0]));
  PKIBody body = new PKIBody(PKIBody.TYPE_REVOCATION_REQ, content);
  return new PKIMessage(header, body);
}
 
Example 30
private ASN1Primitive createDERForRecipient(byte[] in, X509Certificate cert) 
    throws IOException,  
           GeneralSecurityException 
{
    
    String s = "1.2.840.113549.3.2";
    
    AlgorithmParameterGenerator algorithmparametergenerator = AlgorithmParameterGenerator.getInstance(s);
    AlgorithmParameters algorithmparameters = algorithmparametergenerator.generateParameters();
    ByteArrayInputStream bytearrayinputstream = new ByteArrayInputStream(algorithmparameters.getEncoded("ASN.1"));
    ASN1InputStream asn1inputstream = new ASN1InputStream(bytearrayinputstream);
    ASN1Primitive derobject = asn1inputstream.readObject();
    KeyGenerator keygenerator = KeyGenerator.getInstance(s);
    keygenerator.init(128);
    SecretKey secretkey = keygenerator.generateKey();
    Cipher cipher = Cipher.getInstance(s);
    cipher.init(1, secretkey, algorithmparameters);
    byte[] abyte1 = cipher.doFinal(in);
    DEROctetString deroctetstring = new DEROctetString(abyte1);
    KeyTransRecipientInfo keytransrecipientinfo = computeRecipientInfo(cert, secretkey.getEncoded());
    DERSet derset = new DERSet(new RecipientInfo(keytransrecipientinfo));
    AlgorithmIdentifier algorithmidentifier = new AlgorithmIdentifier(new ASN1ObjectIdentifier(s), derobject);
    EncryptedContentInfo encryptedcontentinfo = 
        new EncryptedContentInfo(PKCSObjectIdentifiers.data, algorithmidentifier, deroctetstring);
    EnvelopedData env = new EnvelopedData(null, derset, encryptedcontentinfo, (org.bouncycastle.asn1.ASN1Set) null);
    ContentInfo contentinfo = 
        new ContentInfo(PKCSObjectIdentifiers.envelopedData, env);
    return contentinfo.toASN1Primitive();        
}