Java Code Examples for org.bouncycastle.asn1.ASN1Sequence

The following examples show how to use org.bouncycastle.asn1.ASN1Sequence. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: xipki   Source File: ProxyMessage.java    License: Apache License 2.0 6 votes vote down vote up
public static ObjectIdAndCert getInstance(Object obj) throws BadAsn1ObjectException {
  if (obj == null || obj instanceof ObjectIdAndCert) {
    return (ObjectIdAndCert) obj;
  }

  try {
    if (obj instanceof ASN1Sequence) {
      return new ObjectIdAndCert((ASN1Sequence) obj);
    } else if (obj instanceof byte[]) {
      return getInstance(ASN1Primitive.fromByteArray((byte[]) obj));
    } else {
      throw new BadAsn1ObjectException("unknown object: " + obj.getClass().getName());
    }
  } catch (IOException | IllegalArgumentException ex) {
    throw new BadAsn1ObjectException("unable to parse object: " + ex.getMessage(), ex);
  }
}
 
Example 2
Source Project: SAMLRaider   Source File: BurpCertificate.java    License: MIT License 6 votes vote down vote up
public String getAuthorityKeyIdentifier() {
	byte[] e = certificate.getExtensionValue(Extension.authorityKeyIdentifier.getId());

	if (e == null) {
		return "";
	}

	ASN1Primitive ap;
	byte[] k = {};
	try {
		ap = JcaX509ExtensionUtils.parseExtensionValue(e);
		k = ASN1Sequence.getInstance(ap.getEncoded()).getEncoded();
	} catch (IOException e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	}
	// Very ugly hack to extract the SHA1 Hash (59 Hex Chars) from the
	// Extension :(
	return CertificateHelper.addHexColons(CertificateHelper.byteArrayToHex(k)).substring(12, k.length * 3 - 1);
}
 
Example 3
Source Project: xipki   Source File: ProxyMessage.java    License: Apache License 2.0 6 votes vote down vote up
public static NewKeyControl getInstance(Object obj) throws BadAsn1ObjectException {
  if (obj == null || obj instanceof NewKeyControl) {
    return (NewKeyControl) obj;
  }

  try {
    if (obj instanceof ASN1Sequence) {
      return new NewKeyControl((ASN1Sequence) obj);
    } else if (obj instanceof byte[]) {
      return getInstance(ASN1Primitive.fromByteArray((byte[]) obj));
    } else {
      throw new BadAsn1ObjectException("unknown object: " + obj.getClass().getName());
    }
  } catch (IOException | IllegalArgumentException ex) {
    throw new BadAsn1ObjectException("unable to parse object: " + ex.getMessage(), ex);
  }
}
 
Example 4
Source Project: keystore-explorer   Source File: Spkac.java    License: GNU General Public License v3.0 6 votes vote down vote up
private PublicKey decodePublicKeyFromBitString(ASN1ObjectIdentifier publicKeyAlgorithmOid,
		ASN1Primitive algorithmParameters, DERBitString publicKey) throws SpkacException {
	if (publicKeyAlgorithmOid.getId().equals(RSA.oid())) {
		return decodeRsaPublicKeyFromBitString(publicKey); // Algorithm parameters are ASN1Null and unnecessary
	} else if (publicKeyAlgorithmOid.getId().equals(DSA.oid())) {
		ASN1Sequence dssParams = (ASN1Sequence) algorithmParameters;

		BigInteger p = ((ASN1Integer) dssParams.getObjectAt(0)).getValue();
		BigInteger q = ((ASN1Integer) dssParams.getObjectAt(1)).getValue();
		BigInteger g = ((ASN1Integer) dssParams.getObjectAt(2)).getValue();

		return decodeDsaPublicKeyFromBitString(publicKey, p, q, g);
	} else {
		throw new SpkacException(MessageFormat.format(
				res.getString("NoSupportPublicKeyAlgorithm.exception.message"), publicKeyAlgorithmOid.getId()));

	}
}
 
Example 5
@Override
protected List<Identifier> getEncapsulatedCertificateIdentifiers(CAdESAttribute unsignedAttribute) {
	List<Identifier> certificateIdentifiers = new ArrayList<>();
	ASN1Sequence seq = (ASN1Sequence) unsignedAttribute.getASN1Object();
	for (int ii = 0; ii < seq.size(); ii++) {
		try {
			final Certificate cs = Certificate.getInstance(seq.getObjectAt(ii));
			CertificateToken certificateToken = DSSUtils.loadCertificate(cs.getEncoded());
			certificateIdentifiers.add(certificateToken.getDSSId());
		} catch (Exception e) {
			String errorMessage = "Unable to parse an encapsulated certificate : {}";
			if (LOG.isDebugEnabled()) {
				LOG.warn(errorMessage, e.getMessage(), e);
			} else {
				LOG.warn(errorMessage, e.getMessage());
			}
		}
	}
	return certificateIdentifiers;
}
 
Example 6
Source Project: xipki   Source File: ExtensionSyntaxChecker.java    License: Apache License 2.0 6 votes vote down vote up
private static void checkContentTextOrSubFields(String name, ExtnSyntax subField,
    ASN1Encodable obj) throws BadCertTemplateException {
  if (obj instanceof ASN1String) {
    if (subField.getStringRegex() != null) {
      assertMatch(name, subField.getStringRegex(), ((ASN1String) obj).getString());
    }
    return;
  }

  FieldType syntaxType = subField.type();
  if (syntaxType == FieldType.SEQUENCE) {
    checkSequenceSyntax(name, (ASN1Sequence) obj, subField.getSubFields());
  } else if (syntaxType == FieldType.SET) {
    checkSetSyntax(name, (ASN1Set) obj, subField.getSubFields());
  } else if (syntaxType == FieldType.SEQUENCE_OF) {
    checkSequenceOfOrSetOfSyntax(name, (ASN1Sequence) obj, null, subField.getSubFields());
  } else if (syntaxType == FieldType.SET_OF) {
    checkSequenceOfOrSetOfSyntax(name, null, (ASN1Set) obj, subField.getSubFields());
  }
}
 
Example 7
Source Project: dss   Source File: CMSOCSPSource.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
private void collectRevocationRefs(AttributeTable unsignedAttributes, ASN1ObjectIdentifier revocationReferencesAttribute, RevocationRefOrigin origin) {
	final Attribute attribute = unsignedAttributes.get(revocationReferencesAttribute);
	if (attribute == null) {
		return;
	}
	final ASN1Set attrValues = attribute.getAttrValues();
	if (attrValues.size() <= 0) {
		return;
	}

	final ASN1Encodable attrValue = attrValues.getObjectAt(0);
	final ASN1Sequence completeRevocationRefs = (ASN1Sequence) attrValue;
	for (int i = 0; i < completeRevocationRefs.size(); i++) {

		final CrlOcspRef otherCertId = CrlOcspRef.getInstance(completeRevocationRefs.getObjectAt(i));
		final OcspListID ocspListID = otherCertId.getOcspids();
		if (ocspListID != null) {
			for (final OcspResponsesID ocspResponsesID : ocspListID.getOcspResponses()) {
				final OCSPRef ocspRef = new OCSPRef(ocspResponsesID);
				addRevocationReference(ocspRef, origin);
			}
		}
	}
}
 
Example 8
Source Project: Auditor   Source File: AttestationPackageInfo.java    License: MIT License 6 votes vote down vote up
public AttestationPackageInfo(ASN1Encodable asn1Encodable) throws CertificateParsingException {
    if (!(asn1Encodable instanceof ASN1Sequence)) {
        throw new CertificateParsingException(
                "Expected sequence for AttestationPackageInfo, found "
                        + asn1Encodable.getClass().getName());
    }

    ASN1Sequence sequence = (ASN1Sequence) asn1Encodable;
    try {
        packageName = Asn1Utils.getStringFromAsn1OctetStreamAssumingUTF8(
                sequence.getObjectAt(PACKAGE_NAME_INDEX));
    } catch (UnsupportedEncodingException e) {
        throw new CertificateParsingException(
                "Converting octet stream to String triggered an UnsupportedEncodingException",
                e);
    }
    version = Asn1Utils.getLongFromAsn1(sequence.getObjectAt(VERSION_INDEX));
}
 
Example 9
Source Project: AttestationServer   Source File: Asn1Utils.java    License: MIT License 6 votes vote down vote up
public static ASN1Sequence getAsn1SequenceFromStream(final ASN1InputStream asn1InputStream)
        throws IOException, CertificateParsingException {
    ASN1Primitive asn1Primitive = asn1InputStream.readObject();
    if (!(asn1Primitive instanceof ASN1OctetString)) {
        throw new CertificateParsingException(
                "Expected octet stream, found " + asn1Primitive.getClass().getName());
    }
    try (ASN1InputStream seqInputStream = new ASN1InputStream(
            ((ASN1OctetString) asn1Primitive).getOctets())) {
        asn1Primitive = seqInputStream.readObject();
        if (!(asn1Primitive instanceof ASN1Sequence)) {
            throw new CertificateParsingException(
                    "Expected sequence, found " + asn1Primitive.getClass().getName());
        }
        return (ASN1Sequence) asn1Primitive;
    }
}
 
Example 10
Source Project: AttestationServer   Source File: RootOfTrust.java    License: MIT License 6 votes vote down vote up
public RootOfTrust(ASN1Encodable asn1Encodable) throws CertificateParsingException {
    if (!(asn1Encodable instanceof ASN1Sequence)) {
        throw new CertificateParsingException("Expected sequence for root of trust, found "
                + asn1Encodable.getClass().getName());
    }

    ASN1Sequence sequence = (ASN1Sequence) asn1Encodable;
    verifiedBootKey =
            Asn1Utils.getByteArrayFromAsn1(sequence.getObjectAt(VERIFIED_BOOT_KEY_INDEX));
    deviceLocked = Asn1Utils.getBooleanFromAsn1(sequence.getObjectAt(DEVICE_LOCKED_INDEX));
    verifiedBootState =
            Asn1Utils.getIntegerFromAsn1(sequence.getObjectAt(VERIFIED_BOOT_STATE_INDEX));
    if (sequence.size() < 4) {
        verifiedBootHash = null;
        return;
    }
    verifiedBootHash =
            Asn1Utils.getByteArrayFromAsn1(sequence.getObjectAt(VERIFIED_BOOT_HASH_INDEX));
}
 
Example 11
Source Project: AttestationServer   Source File: AttestationPackageInfo.java    License: MIT License 6 votes vote down vote up
public AttestationPackageInfo(ASN1Encodable asn1Encodable) throws CertificateParsingException {
    if (!(asn1Encodable instanceof ASN1Sequence)) {
        throw new CertificateParsingException(
                "Expected sequence for AttestationPackageInfo, found "
                        + asn1Encodable.getClass().getName());
    }

    ASN1Sequence sequence = (ASN1Sequence) asn1Encodable;
    try {
        packageName = Asn1Utils.getStringFromAsn1OctetStreamAssumingUTF8(
                sequence.getObjectAt(PACKAGE_NAME_INDEX));
    } catch (UnsupportedEncodingException e) {
        throw new CertificateParsingException(
                "Converting octet stream to String triggered an UnsupportedEncodingException",
                e);
    }
    version = Asn1Utils.getLongFromAsn1(sequence.getObjectAt(VERSION_INDEX));
}
 
Example 12
Source Project: xipki   Source File: ProxyMessage.java    License: Apache License 2.0 6 votes vote down vote up
public static RemoveObjectsParams getInstance(Object obj) throws BadAsn1ObjectException {
  if (obj == null || obj instanceof RemoveObjectsParams) {
    return (RemoveObjectsParams) obj;
  }

  try {
    if (obj instanceof ASN1Sequence) {
      return new RemoveObjectsParams((ASN1Sequence) obj);
    } else if (obj instanceof byte[]) {
      return getInstance(ASN1Primitive.fromByteArray((byte[]) obj));
    } else {
      throw new BadAsn1ObjectException("unknown object: " + obj.getClass().getName());
    }
  } catch (IOException | IllegalArgumentException ex) {
    throw new BadAsn1ObjectException("unable to parse encoded object: " + ex.getMessage(), ex);
  }
}
 
Example 13
Source Project: factura-electronica   Source File: CFDv3Debugger.java    License: Apache License 2.0 6 votes vote down vote up
private void dumpDigests() throws Exception {
    System.err.println(cfd.getCadenaOriginal());
    String certStr = cfd.document.getCertificado();
    Base64 b64 = new Base64();
    byte[] cbs = b64.decode(certStr);
    X509Certificate cert = (X509Certificate) KeyLoaderFactory.createInstance(
            KeyLoaderEnumeration.PUBLIC_KEY_LOADER,
            new ByteArrayInputStream(cbs)).getKey();
    cert.checkValidity();
    String sigStr = cfd.document.getSello();
    byte[] signature = b64.decode(sigStr);
    CFDv3.dump("Digestion firmada", signature, System.err);
    Cipher dec = Cipher.getInstance("RSA");
    dec.init(Cipher.DECRYPT_MODE, cert);
    byte[] result = dec.doFinal(signature);
    CFDv3.dump("Digestion decriptada", result, System.err);
    ASN1InputStream aIn = new ASN1InputStream(result);
    ASN1Sequence seq = (ASN1Sequence) aIn.readObject();
    ASN1OctetString sigHash = (ASN1OctetString) seq.getObjectAt(1);
    CFDv3.dump("Sello", sigHash.getOctets(), System.err);
}
 
Example 14
Source Project: xipki   Source File: CaClientExample.java    License: Apache License 2.0 6 votes vote down vote up
protected static MyKeypair generateDsaKeypair() throws Exception {
  // plen: 2048, qlen: 256
  DSAParameterSpec spec = new DSAParameterSpec(P2048_Q256_P, P2048_Q256_Q, P2048_Q256_G);
  KeyPairGenerator kpGen = KeyPairGenerator.getInstance("DSA");
  kpGen.initialize(spec);
  KeyPair kp = kpGen.generateKeyPair();

  DSAPublicKey dsaPubKey = (DSAPublicKey) kp.getPublic();
  ASN1EncodableVector vec = new ASN1EncodableVector();
  vec.add(new ASN1Integer(dsaPubKey.getParams().getP()));
  vec.add(new ASN1Integer(dsaPubKey.getParams().getQ()));
  vec.add(new ASN1Integer(dsaPubKey.getParams().getG()));
  ASN1Sequence dssParams = new DERSequence(vec);

  SubjectPublicKeyInfo subjectPublicKeyInfo = new SubjectPublicKeyInfo(
      new AlgorithmIdentifier(X9ObjectIdentifiers.id_dsa, dssParams),
      new ASN1Integer(dsaPubKey.getY()));

  return new MyKeypair(kp.getPrivate(), subjectPublicKeyInfo);
}
 
Example 15
Source Project: xipki   Source File: ProxyMessage.java    License: Apache License 2.0 6 votes vote down vote up
public static ObjectIdentifiers getInstance(Object obj) throws BadAsn1ObjectException {
  if (obj == null || obj instanceof ObjectIdentifiers) {
    return (ObjectIdentifiers) obj;
  }

  try {
    if (obj instanceof ASN1Sequence) {
      return new ObjectIdentifiers((ASN1Sequence) obj);
    } else if (obj instanceof byte[]) {
      return getInstance(ASN1Primitive.fromByteArray((byte[]) obj));
    } else {
      throw new BadAsn1ObjectException("unknown object: " + obj.getClass().getName());
    }
  } catch (IOException | IllegalArgumentException ex) {
    throw new BadAsn1ObjectException("unable to parse encoded object: " + ex.getMessage(), ex);
  }
}
 
Example 16
Source Project: web3sdk   Source File: SM2Signer.java    License: Apache License 2.0 6 votes vote down vote up
public BigInteger[] derDecode(byte[] encoding) throws IOException {
    ASN1Sequence seq = ASN1Sequence.getInstance(ASN1Primitive.fromByteArray(encoding));
    if (seq.size() != 2) {
        return null;
    }

    BigInteger r = ASN1Integer.getInstance(seq.getObjectAt(0)).getValue();
    BigInteger s = ASN1Integer.getInstance(seq.getObjectAt(1)).getValue();

    byte[] expectedEncoding = derEncode(r, s);
    if (!Arrays.constantTimeAreEqual(expectedEncoding, encoding)) {
        return null;
    }

    return new BigInteger[] {r, s};
}
 
Example 17
Source Project: signer   Source File: PolicyInfo.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void parse(ASN1Primitive derObject) {
    ASN1Sequence derSequence = ASN1Object.getDERSequence(derObject);
    ASN1Primitive firstObject = derSequence.getObjectAt(0).toASN1Primitive();
    this.policyName = new DirectoryString(firstObject.toString());
    ASN1Primitive secondObject = derSequence.getObjectAt(1).toASN1Primitive();
    String fieldOfApplication = secondObject.toString();
    this.fieldOfApplication = new DirectoryString(fieldOfApplication);
    this.signingPeriod = new SigningPeriod();
    this.signingPeriod.parse(derSequence.getObjectAt(2).toASN1Primitive());

    int indice = 3;
    ASN1Primitive revocationObject = derSequence.getObjectAt(indice).toASN1Primitive();
    if (!(secondObject instanceof DERTaggedObject)) {
        indice = 4;
    }
    if (indice == 3) {
        this.revocationDate = new Time();
        this.revocationDate.parse(revocationObject);
    }
}
 
Example 18
Source Project: dss   Source File: DSSASN1Utils.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Gets the ASN.1 algorithm identifier structure corresponding to the algorithm 
 * found in the provided Timestamp Hash Index Table, if such algorithm is present
 *
 * @param atsHashIndexValue
 *            ats-hash-index table from a timestamp
 * @return the ASN.1 algorithm identifier structure
 */
public static AlgorithmIdentifier getAlgorithmIdentifier(final ASN1Sequence atsHashIndexValue) {
	if (atsHashIndexValue != null && atsHashIndexValue.size() > 3) {
		final int algorithmIndex = 0;
		final ASN1Encodable asn1Encodable = atsHashIndexValue.getObjectAt(algorithmIndex);
		
		if (asn1Encodable instanceof ASN1Sequence) {
			final ASN1Sequence asn1Sequence = (ASN1Sequence) asn1Encodable;
			return AlgorithmIdentifier.getInstance(asn1Sequence);
		} else if (asn1Encodable instanceof ASN1ObjectIdentifier) {
			// TODO (16/11/2014): The relevance and usefulness of the test case must be checked (do the signatures
			// like this exist?)
			ASN1ObjectIdentifier derObjectIdentifier = ASN1ObjectIdentifier.getInstance(asn1Encodable);
			return new AlgorithmIdentifier(derObjectIdentifier);
		}
	}
	return null;
}
 
Example 19
Source Project: signer   Source File: LPA.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void parse(ASN1Primitive derObject) {
    ASN1Sequence sequence = ASN1Object.getDERSequence(derObject);
    ASN1Primitive policyInfos = sequence.getObjectAt(0).toASN1Primitive();
    DLSequence policyInfosSequence = (DLSequence) policyInfos;
    if (policyInfosSequence != null && policyInfosSequence.size() > 0) {
        this.policyInfos = new ArrayList<>();
        for (int i = 0; i < policyInfosSequence.size(); i++) {
            PolicyInfo policyInfo = new PolicyInfo();
            policyInfo.parse(policyInfosSequence.getObjectAt(i).toASN1Primitive());
            this.policyInfos.add(policyInfo);
        }
    }
    this.nextUpdate = new Time();
    this.nextUpdate.parse(sequence.getObjectAt(1).toASN1Primitive());
}
 
Example 20
Source Project: xipki   Source File: ProxyMessage.java    License: Apache License 2.0 6 votes vote down vote up
public static GenECKeypairParams getInstance(Object obj) throws BadAsn1ObjectException {
  if (obj == null || obj instanceof GenECKeypairParams) {
    return (GenECKeypairParams) obj;
  }

  try {
    if (obj instanceof ASN1Sequence) {
      return new GenECKeypairParams((ASN1Sequence) obj);
    } else if (obj instanceof byte[]) {
      return getInstance(ASN1Primitive.fromByteArray((byte[]) obj));
    } else {
      throw new BadAsn1ObjectException("unknown object: " + obj.getClass().getName());
    }
  } catch (IOException | IllegalArgumentException ex) {
    throw new BadAsn1ObjectException("unable to parse encoded object: " + ex.getMessage(), ex);
  }
}
 
Example 21
Source Project: xipki   Source File: ProxyMessage.java    License: Apache License 2.0 6 votes vote down vote up
public static Mechanism getInstance(Object obj) throws BadAsn1ObjectException {
  if (obj == null || obj instanceof Mechanism) {
    return (Mechanism) obj;
  }

  try {
    if (obj instanceof ASN1Sequence) {
      return new Mechanism((ASN1Sequence) obj);
    } else if (obj instanceof byte[]) {
      return getInstance(ASN1Primitive.fromByteArray((byte[]) obj));
    } else {
      throw new BadAsn1ObjectException("unknown object: " + obj.getClass().getName());
    }
  } catch (IOException | IllegalArgumentException ex) {
    throw new BadAsn1ObjectException("unable to parse encoded object: " + ex.getMessage(), ex);
  }
}
 
Example 22
Source Project: dss   Source File: DSSASN1Utils.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
public static List<String> getQCLegislations(CertificateToken certToken) {
	final List<String> result = new ArrayList<>();
	final byte[] qcStatement = certToken.getCertificate().getExtensionValue(Extension.qCStatements.getId());
	if (Utils.isArrayNotEmpty(qcStatement)) {
		try {
			final ASN1Sequence seq = getAsn1SequenceFromDerOctetString(qcStatement);
			// Sequence of QCStatement
			for (int ii = 0; ii < seq.size(); ii++) {
				final QCStatement statement = QCStatement.getInstance(seq.getObjectAt(ii));
				if (QC_LEGISLATION_OID.equals(statement.getStatementId().getId())) {
					ASN1Sequence sequenceLegislation = ASN1Sequence.getInstance(statement.getStatementInfo());
					for (int jj = 0; jj < sequenceLegislation.size(); jj++) {
						result.add(getString(sequenceLegislation.getObjectAt(jj)));
					}
					
				}
			}
		} catch (Exception e) {
			LOG.warn("Unable to parse the qCStatements extension '{}' : {}", Utils.toBase64(qcStatement), e.getMessage(), e);
		}
	}
	return result;
}
 
Example 23
Source Project: signer   Source File: LPA.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
public void parse(ASN1Primitive derObject) {
    ASN1Sequence sequence = ASN1Object.getDERSequence(derObject);
    ASN1Primitive firstObject = sequence.getObjectAt(0).toASN1Primitive();
    this.version = new Version();
    int indice = 0;
    if (firstObject instanceof ASN1Integer) {
        this.version.parse(firstObject);
        indice++;
    }
    ASN1Primitive policyInfos = sequence.getObjectAt(indice).toASN1Primitive();
    DLSequence policyInfosSequence = (DLSequence) policyInfos;
    if (policyInfosSequence != null && policyInfosSequence.size() > 0) {
        this.policyInfos = new ArrayList<>();
        for (int i = 0; i < policyInfosSequence.size(); i++) {
            PolicyInfo policyInfo = new PolicyInfo();
            policyInfo.parse(policyInfosSequence.getObjectAt(i).toASN1Primitive());
            this.policyInfos.add(policyInfo);
        }
    }
    this.nextUpdate = new GeneralizedTime();
    this.nextUpdate.parse(sequence.getObjectAt(indice + 1).toASN1Primitive());
}
 
Example 24
Source Project: dss   Source File: DSSASN1Utils.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
public static IssuerSerial getIssuerSerial(byte[] binaries) {
	try (ASN1InputStream is = new ASN1InputStream(binaries)) {
		ASN1Sequence seq = (ASN1Sequence) is.readObject();
		return IssuerSerial.getInstance(seq);
	} catch (Exception e) {
		LOG.error("Unable to decode IssuerSerialV2 textContent '{}' : {}", Utils.toBase64(binaries), e.getMessage(), e);
		return null;
	}
}
 
Example 25
Source Project: keystore-explorer   Source File: Spkac.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void decodeSpkac(byte[] der) throws SpkacException {
	try {
		ASN1Sequence signedPublicKeyAndChallenge = ASN1Sequence.getInstance(der);

		ASN1Sequence publicKeyAndChallenge = (ASN1Sequence) signedPublicKeyAndChallenge.getObjectAt(0);
		ASN1Sequence signatureAlgorithm = (ASN1Sequence) signedPublicKeyAndChallenge.getObjectAt(1);
		DERBitString signature = (DERBitString) signedPublicKeyAndChallenge.getObjectAt(2);

		ASN1ObjectIdentifier signatureAlgorithmOid = (ASN1ObjectIdentifier) signatureAlgorithm.getObjectAt(0);

		ASN1Sequence spki = (ASN1Sequence) publicKeyAndChallenge.getObjectAt(0);
		DERIA5String challenge = (DERIA5String) publicKeyAndChallenge.getObjectAt(1);

		ASN1Sequence publicKeyAlgorithm = (ASN1Sequence) spki.getObjectAt(0);
		DERBitString publicKey = (DERBitString) spki.getObjectAt(1);

		ASN1ObjectIdentifier publicKeyAlgorithmOid = (ASN1ObjectIdentifier) publicKeyAlgorithm.getObjectAt(0);
		ASN1Primitive algorithmParameters = publicKeyAlgorithm.getObjectAt(1).toASN1Primitive();

		this.challenge = challenge.getString();
		this.publicKey = decodePublicKeyFromBitString(publicKeyAlgorithmOid, algorithmParameters, publicKey);
		this.signatureAlgorithm = getSignatureAlgorithm(signatureAlgorithmOid);
		this.signature = signature.getBytes();
	} catch (Exception ex) {
		throw new SpkacException(res.getString("NoDecodeSpkac.exception.message"), ex);
	}
}
 
Example 26
Source Project: ofdrw   Source File: VersionParser.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 解析电子印章版本
 *
 * @param o 带解析数据,可以是字节串也可以是ASN1对象
 * @return 带有版本的ASN1对象序列
 */
public static SESVersionHolder parseSES_SealVersion(Object o) {
    ASN1Sequence seq = ASN1Sequence.getInstance(o);
    SESVersion version;
    if (seq.size() == 4) {
        /*
         * GB/T 38540-2020 信息安全技术 安全电子签章密码技术规范 电子印章数据
         *
         * - 印章信息
         * - 制章者证书
         * - 签名算法标识符
         * - 签名值
         */
        version = SESVersion.v4;
    } else if (seq.size() == 2) {
        /*
         * GM/T 0031-2014 安全电子签章密码技术规范 电子印章数据
         *
         * - 印章信息
         * - 制章人对印章签名的信息
         */
        version = SESVersion.v1;
    } else {
        throw new IllegalArgumentException("未知的数据结构,无法匹配任何已知版本电子印章。");
    }
    return new SESVersionHolder(version, seq);
}
 
Example 27
Source Project: xipki   Source File: ExtensionExistence.java    License: Apache License 2.0 5 votes vote down vote up
private ExtensionExistence(ASN1Sequence seq) {
  int size = seq.size();
  if (size > 2) {
    throw new IllegalArgumentException("wrong number of elements in sequence");
  }

  for (int i = 0; i < size; i++) {
    ASN1TaggedObject tagObject = ASN1TaggedObject.getInstance(seq.getObjectAt(i));
    int tag = tagObject.getTagNo();
    Args.range(tag, "tag", 0, 1);
    ASN1Sequence subSeq = ASN1Sequence.getInstance(tagObject.getObject());
    List<ASN1ObjectIdentifier> oids = new LinkedList<>();
    int subSize = subSeq.size();
    for (int j = 0; j < subSize; j++) {
      oids.add(ASN1ObjectIdentifier.getInstance(subSeq.getObjectAt(j)));
    }

    if (tag == 0) {
      needExtensions = Collections.unmodifiableList(oids);
    } else {
      wantExtensions = Collections.unmodifiableList(oids);
    }
  }

  if (needExtensions == null) {
    needExtensions = Collections.unmodifiableList(Collections.emptyList());
  }

  if (wantExtensions == null) {
    wantExtensions = Collections.unmodifiableList(Collections.emptyList());
  }
}
 
Example 28
Source Project: dss   Source File: DSSASN1Utils.java    License: 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 29
Source Project: dss   Source File: DSSSignatureUtils.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Checks if the signature is ASN.1 encoded.
 *
 * @param signatureValue
 *            signature value to check.
 * @return if the signature is ASN.1 encoded.
 */
private static boolean isAsn1Encoded(byte[] signatureValue) {
	try (ASN1InputStream is = new ASN1InputStream(signatureValue)) {
		ASN1Sequence seq = (ASN1Sequence) is.readObject();
		return seq != null && seq.size() == 2;
	} catch (Exception e) {
		return false;
	}
}
 
Example 30
Source Project: xipki   Source File: SignerUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static byte[] dsaSigX962ToPlain(byte[] x962Signature, int keyBitLen)
    throws XiSecurityException {
  Args.notNull(x962Signature, "x962Signature");
  ASN1Sequence seq = ASN1Sequence.getInstance(x962Signature);
  if (seq.size() != 2) {
    throw new IllegalArgumentException("invalid X962Signature");
  }
  BigInteger sigR = ASN1Integer.getInstance(seq.getObjectAt(0)).getPositiveValue();
  BigInteger sigS = ASN1Integer.getInstance(seq.getObjectAt(1)).getPositiveValue();
  return dsaSigToPlain(sigR, sigS, keyBitLen);
}