Java Code Examples for org.bouncycastle.asn1.ASN1OctetString

The following examples show how to use org.bouncycastle.asn1.ASN1OctetString. 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: Auditor   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 2
Source Project: hedera-sdk-java   Source File: Ed25519PrivateKey.java    License: Apache License 2.0 6 votes vote down vote up
private static Ed25519PrivateKey fromPrivateKeyInfo(PrivateKeyInfo privateKeyInfo) {
    Ed25519PrivateKeyParameters privKeyParams;
    Ed25519PublicKeyParameters pubKeyParams = null;

    try {
        ASN1Encodable privateKey = privateKeyInfo.parsePrivateKey();
        privKeyParams = new Ed25519PrivateKeyParameters(((ASN1OctetString) privateKey).getOctets(), 0);

        ASN1BitString pubKeyData = privateKeyInfo.getPublicKeyData();

        if (pubKeyData != null) {
            pubKeyParams = new Ed25519PublicKeyParameters(pubKeyData.getOctets(), 0);
        }

    } catch (IOException e) {
        throw new BadKeyException(e);
    }

    if (pubKeyParams != null) {
        return new Ed25519PrivateKey(privKeyParams, pubKeyParams);
    } else {
        return new Ed25519PrivateKey(privKeyParams);
    }
}
 
Example 3
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 4
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 5
Source Project: snowflake-jdbc   Source File: SFTrustManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Convert cache key to base64 encoded
 * cert id
 *
 * @param ocsp_cache_key Cache key to encode
 */
private static String encodeCacheKey(OcspResponseCacheKey ocsp_cache_key)
{
  try
  {
    DigestCalculator digest = new SHA1DigestCalculator();
    AlgorithmIdentifier algo = digest.getAlgorithmIdentifier();
    ASN1OctetString nameHash = ASN1OctetString.getInstance(ocsp_cache_key.nameHash);
    ASN1OctetString keyHash = ASN1OctetString.getInstance(ocsp_cache_key.keyHash);
    ASN1Integer snumber = new ASN1Integer(ocsp_cache_key.serialNumber);
    CertID cid = new CertID(algo, nameHash, keyHash, snumber);
    return Base64.encodeBase64String(cid.toASN1Primitive().getEncoded());
  }
  catch (Exception ex)
  {
    LOGGER.debug("Failed to encode cache key to base64 encoded cert id");
  }
  return null;
}
 
Example 6
Source Project: snowflake-jdbc   Source File: SSDManager.java    License: Apache License 2.0 6 votes vote down vote up
SFTrustManager.OcspResponseCacheKey getWildCardCertId()
{
  DigestCalculator digest = new SFTrustManager.SHA1DigestCalculator();
  AlgorithmIdentifier algo = digest.getAlgorithmIdentifier();
  ASN1OctetString nameHash = ASN1OctetString.getInstance("0");
  ASN1OctetString keyHash = ASN1OctetString.getInstance("0");
  ASN1Integer serial_number = ASN1Integer.getInstance(0);
  CertID cid = new CertID(algo, nameHash, keyHash, serial_number);
  SFTrustManager.OcspResponseCacheKey keyOcspResp = null;
  try
  {
    keyOcspResp = new SFTrustManager.OcspResponseCacheKey(
        ASN1OctetString.getInstance("0").getEncoded(),
        ASN1OctetString.getInstance("0").getEncoded(),
        ASN1Integer.getInstance(0).getValue());
  }
  catch (Throwable ex)
  {
    LOGGER.debug("Could not create wildcard certid as cache key");
    keyOcspResp = null;
  }
  return keyOcspResp;
}
 
Example 7
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 8
private ParsedAttestationRecord(ASN1Sequence extensionData) {
  this.attestationVersion =
      ASN1Parsing.getIntegerFromAsn1(extensionData.getObjectAt(ATTESTATION_VERSION_INDEX));
  this.attestationSecurityLevel =
      securityLevelToEnum(
          ASN1Parsing.getIntegerFromAsn1(
              extensionData.getObjectAt(ATTESTATION_SECURITY_LEVEL_INDEX)));
  this.keymasterVersion =
      ASN1Parsing.getIntegerFromAsn1(extensionData.getObjectAt(KEYMASTER_VERSION_INDEX));
  this.keymasterSecurityLevel =
      securityLevelToEnum(
          ASN1Parsing.getIntegerFromAsn1(
              extensionData.getObjectAt(KEYMASTER_SECURITY_LEVEL_INDEX)));
  this.attestationChallenge =
      ((ASN1OctetString) extensionData.getObjectAt(ATTESTATION_CHALLENGE_INDEX)).getOctets();
  this.uniqueId = ((ASN1OctetString) extensionData.getObjectAt(UNIQUE_ID_INDEX)).getOctets();
  this.softwareEnforced =
      AuthorizationList.createAuthorizationList(
          ((ASN1Sequence) extensionData.getObjectAt(SW_ENFORCED_INDEX)).toArray(),
          attestationVersion);
  this.teeEnforced =
      AuthorizationList.createAuthorizationList(
          ((ASN1Sequence) extensionData.getObjectAt(TEE_ENFORCED_INDEX)).toArray(),
          attestationVersion);
}
 
Example 9
Source Project: android-key-attestation   Source File: RootOfTrust.java    License: Apache License 2.0 6 votes vote down vote up
private RootOfTrust(ASN1Sequence rootOfTrust, int attestationVersion) {
  this.verifiedBootKey =
      ((ASN1OctetString) rootOfTrust.getObjectAt(ROOT_OF_TRUST_VERIFIED_BOOT_KEY_INDEX))
          .getOctets();
  this.deviceLocked =
      ASN1Parsing.getBooleanFromAsn1(rootOfTrust.getObjectAt(ROOT_OF_TRUST_DEVICE_LOCKED_INDEX));
  this.verifiedBootState =
      verifiedBootStateToEnum(
          ASN1Parsing.getIntegerFromAsn1(
              rootOfTrust.getObjectAt(ROOT_OF_TRUST_VERIFIED_BOOT_STATE_INDEX)));
  if (attestationVersion >= 3) {
    this.verifiedBootHash =
        ((ASN1OctetString) rootOfTrust.getObjectAt(ROOT_OF_TRUST_VERIFIED_BOOT_HASH_INDEX))
            .getOctets();
  } else {
    this.verifiedBootHash = null;
  }
}
 
Example 10
Source Project: keystore-explorer   Source File: Asn1Dump.java    License: GNU General Public License v3.0 6 votes vote down vote up
private String dumpOctetString(ASN1OctetString asn1OctetString) throws IOException {
	StringBuilder sb = new StringBuilder();
	byte[] bytes = asn1OctetString.getOctets();

	sb.append(indentSequence.toString(indentLevel));
	sb.append("OCTET STRING");
	try {
		String encapsulated = dump(bytes);
		sb.append(", encapsulates:");
		sb.append(NEWLINE);
		sb.append(encapsulated);
	} catch (Exception e) {
		sb.append("=");
		if (bytes.length < 8) {
			sb.append(HexUtil.getHexString(bytes));
		} else {
			sb.append(NEWLINE);
			sb.append(dumpHexClear(bytes));
		}
	}
	sb.append(NEWLINE);

	return sb.toString();
}
 
Example 11
Source Project: SAMLRaider   Source File: BurpCertificate.java    License: MIT License 6 votes vote down vote up
public String getSubjectKeyIdentifier() {
	// https://stackoverflow.com/questions/6523081/why-doesnt-my-key-identifier-match
	byte[] e = certificate.getExtensionValue(Extension.subjectKeyIdentifier.getId());

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

	ASN1Primitive ap;
	byte[] k = {};
	try {
		ap = JcaX509ExtensionUtils.parseExtensionValue(e);
		k = ASN1OctetString.getInstance(ap.getEncoded()).getOctets();
	} catch (IOException e1) {
		e1.printStackTrace();
	}
	return CertificateHelper.addHexColons(CertificateHelper.byteArrayToHex(k));
}
 
Example 12
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 13
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 14
Source Project: android-testdpc   Source File: Asn1Utils.java    License: Apache License 2.0 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 15
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 16
Source Project: xipki   Source File: CmpResponder.java    License: Apache License 2.0 6 votes vote down vote up
private boolean revokePendingCertificates(ASN1OctetString transactionId, String msgId) {
  Set<CertificateInfo> remainingCerts = pendingCertPool.removeCertificates(
      transactionId.getOctets());

  if (CollectionUtil.isEmpty(remainingCerts)) {
    return true;
  }

  boolean successful = true;
  Date invalidityDate = new Date();
  X509Ca ca = getCa();
  for (CertificateInfo remainingCert : remainingCerts) {
    try {
      ca.revokeCert(remainingCert.getCert().getCert().getSerialNumber(),
          CrlReason.CESSATION_OF_OPERATION, invalidityDate, msgId);
    } catch (OperationException ex) {
      successful = false;
    }
  }

  return successful;
}
 
Example 17
Source Project: xipki   Source File: BaseCmpResponder.java    License: Apache License 2.0 6 votes vote down vote up
protected PKIMessage buildErrorPkiMessage(ASN1OctetString tid,
    PKIHeader requestHeader, int failureCode, String statusText) {
  GeneralName respRecipient = requestHeader.getSender();

  PKIHeaderBuilder respHeader = new PKIHeaderBuilder(
      requestHeader.getPvno().getValue().intValue(), getSender(), respRecipient);
  respHeader.setMessageTime(new ASN1GeneralizedTime(new Date()));
  if (tid != null) {
    respHeader.setTransactionID(tid);
  }

  ASN1OctetString senderNonce = requestHeader.getSenderNonce();
  if (senderNonce != null) {
    respHeader.setRecipNonce(senderNonce);
  }

  PKIStatusInfo status = generateRejectionStatus(failureCode, statusText);
  ErrorMsgContent error = new ErrorMsgContent(status);
  PKIBody body = new PKIBody(PKIBody.TYPE_ERROR, error);

  return new PKIMessage(respHeader.build(), body);
}
 
Example 18
Source Project: ofdrw   Source File: SES_SignatureTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
    public void verify() throws IOException, NoSuchAlgorithmException, CertificateException, InvalidKeyException, SignatureException {

        Path path = Paths.get("src/test/resources", "SignedValue.dat");
        Path srcPath = Paths.get("src/test/resources", "Signature.xml");

//        Path path = Paths.get("target", "UserV4.esl");
        SES_Signature sesSignature = SES_Signature.getInstance(Files.readAllBytes(path));

        MessageDigest md = new SM3.Digest();
        byte[] digest = md.digest(Files.readAllBytes(srcPath));
        final ASN1BitString dataHash = sesSignature.getToSign().getDataHash();
        System.out.println(Arrays.equals(digest, dataHash.getOctets()));

        ASN1OctetString cert = sesSignature.getCert();
        CertificateFactory factory = new CertificateFactory();
        X509Certificate certificate = (X509Certificate) factory.engineGenerateCertificate(cert.getOctetStream());

        TBS_Sign toSign = sesSignature.getToSign();

        Signature sg = Signature.getInstance(
                sesSignature.getSignatureAlgID().toString()
                , new BouncyCastleProvider());
        sg.initVerify(certificate);
        sg.update(toSign.getEncoded("DER"));
        byte[] sigVal = sesSignature.getSignature().getBytes();

        System.out.println(sg.verify(sigVal));
    }
 
Example 19
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 20
Source Project: Auditor   Source File: Asn1Utils.java    License: MIT License 5 votes vote down vote up
public static String getStringFromAsn1OctetStreamAssumingUTF8(ASN1Encodable encodable)
        throws CertificateParsingException, UnsupportedEncodingException {
    if (!(encodable instanceof ASN1OctetString)) {
        throw new CertificateParsingException(
                "Expected octet string, found " + encodable.getClass().getName());
    }

    ASN1OctetString octetString = (ASN1OctetString) encodable;
    return new String(octetString.getOctets(), StandardCharsets.UTF_8);
}
 
Example 21
private byte[] getResponderIdByKey() {
   ResponderID responderID = this.ocsp.getResponderId().toASN1Primitive();
   DERTaggedObject derTaggedObject = (DERTaggedObject)responderID.toASN1Primitive();
   if (2 == derTaggedObject.getTagNo()) {
      ASN1OctetString keyHashOctetString = (ASN1OctetString)derTaggedObject.getObject();
      return keyHashOctetString.getOctets();
   } else {
      return new byte[0];
   }
}
 
Example 22
private byte[] getResponderIdByKey() {
   ResponderID responderID = this.ocsp.getResponderId().toASN1Primitive();
   DERTaggedObject derTaggedObject = (DERTaggedObject)responderID.toASN1Primitive();
   if (2 == derTaggedObject.getTagNo()) {
      ASN1OctetString keyHashOctetString = (ASN1OctetString)derTaggedObject.getObject();
      return keyHashOctetString.getOctets();
   } else {
      return new byte[0];
   }
}
 
Example 23
private byte[] getResponderIdByKey() {
   ResponderID responderID = this.ocsp.getResponderId().toASN1Primitive();
   DERTaggedObject derTaggedObject = (DERTaggedObject)responderID.toASN1Primitive();
   if (2 == derTaggedObject.getTagNo()) {
      ASN1OctetString keyHashOctetString = (ASN1OctetString)derTaggedObject.getObject();
      return keyHashOctetString.getOctets();
   } else {
      return new byte[0];
   }
}
 
Example 24
private byte[] getResponderIdByKey() {
   ResponderID responderID = this.ocsp.getResponderId().toASN1Primitive();
   DERTaggedObject derTaggedObject = (DERTaggedObject)responderID.toASN1Primitive();
   if (2 == derTaggedObject.getTagNo()) {
      ASN1OctetString keyHashOctetString = (ASN1OctetString)derTaggedObject.getObject();
      return keyHashOctetString.getOctets();
   } else {
      return new byte[0];
   }
}
 
Example 25
Source Project: AttestationServer   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 26
Source Project: AttestationServer   Source File: Asn1Utils.java    License: MIT License 5 votes vote down vote up
public static String getStringFromAsn1OctetStreamAssumingUTF8(ASN1Encodable encodable)
        throws CertificateParsingException, UnsupportedEncodingException {
    if (!(encodable instanceof ASN1OctetString)) {
        throw new CertificateParsingException(
                "Expected octet string, found " + encodable.getClass().getName());
    }

    ASN1OctetString octetString = (ASN1OctetString) encodable;
    return new String(octetString.getOctets(), StandardCharsets.UTF_8);
}
 
Example 27
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 28
Source Project: gmhelper   Source File: SM2PublicKey.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public byte[] getEncoded() {
    ASN1OctetString p = ASN1OctetString.getInstance(
        new X9ECPoint(getQ(), withCompression).toASN1Primitive());

    // stored curve is null if ImplicitlyCa
    SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(
        new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, ID_SM2_PUBKEY_PARAM),
        p.getOctets());

    return KeyUtil.getEncodedSubjectPublicKeyInfo(info);
}
 
Example 29
public static List<Ct.SignedCertificateTimestamp> parseSCTsFromCert(X509Certificate leafCert)
    throws IOException {
  byte[] bytes = leafCert.getExtensionValue(CTConstants.SCT_CERTIFICATE_OID);
  List<Ct.SignedCertificateTimestamp> scts = new ArrayList<>();
  ASN1Primitive p = ASN1Primitive.fromByteArray(ASN1OctetString.getInstance(bytes).getOctets());
  DEROctetString o = (DEROctetString) p;
  // These are serialized SCTs, we must de-serialize them into an array with one SCT each
  Ct.SignedCertificateTimestamp[] sctsFromCert = parseSCTsFromCertExtension(o.getOctets());
  for (Ct.SignedCertificateTimestamp signedCertificateTimestamp : sctsFromCert) {
    scts.add(signedCertificateTimestamp);
  }
  return scts;
}
 
Example 30
Source Project: fabric-sdk-java   Source File: HFCAX509Certificate.java    License: Apache License 2.0 5 votes vote down vote up
private AuthorityKeyIdentifier getAKI() throws HFCACertificateException {
    if (x509Cert == null) {
        throw new HFCACertificateException("Certificate is null");
    }
    byte[] fullExtValue = x509Cert.getExtensionValue(Extension.authorityKeyIdentifier.getId());
    byte[] extValue = ASN1OctetString.getInstance(fullExtValue).getOctets();
    return AuthorityKeyIdentifier.getInstance(extValue);
}