org.bouncycastle.asn1.ASN1OctetString Java Examples

The following examples show how to use org.bouncycastle.asn1.ASN1OctetString. 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: SSDManager.java    From snowflake-jdbc with 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 #2
Source File: Asn1Utils.java    From AttestationServer with 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 #3
Source File: Ed25519PrivateKey.java    From hedera-sdk-java with 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 #4
Source File: Asn1Utils.java    From Auditor with 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 #5
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 #6
Source File: CFDv3Debugger.java    From factura-electronica with 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 #7
Source File: SFTrustManager.java    From snowflake-jdbc with 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 #8
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 #9
Source File: ParsedAttestationRecord.java    From android-key-attestation with Apache License 2.0 6 votes vote down vote up
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 #10
Source File: RootOfTrust.java    From android-key-attestation with 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 #11
Source File: Asn1Dump.java    From keystore-explorer with 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 #12
Source File: BurpCertificate.java    From SAMLRaider with 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 #13
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 #14
Source File: Asn1Utils.java    From android-testdpc with 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 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 #16
Source File: CmpResponder.java    From xipki with 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 File: BaseCmpResponder.java    From xipki with 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 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 #19
Source File: OcspRef.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
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 #20
Source File: Asn1Utils.java    From android-testdpc with Apache License 2.0 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 File: EncryptedKeys.java    From InflatableDonkey with MIT License 5 votes vote down vote up
public EncryptedKeys(ASN1Primitive primitive) {
    DERIterator i = DER.asSequence(primitive);

    Map<Integer, ASN1Primitive> tagged = i.derTaggedObjects();

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

    encryptedKeySet = DER.asSet(i, EncryptedKey::new);

    cont0 = Optional.ofNullable(tagged.get(CONT0))
            .map(DER.as(DEROctetString.class))
            .map(ASN1OctetString::getOctets);
}
 
Example #22
Source File: AbstractCRLUtils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
protected void extractIssuingDistributionPointBinary(CRLValidity validity, byte[] issuingDistributionPointBinary) {
	if (issuingDistributionPointBinary != null) {
		IssuingDistributionPoint issuingDistributionPoint = IssuingDistributionPoint
				.getInstance(ASN1OctetString.getInstance(issuingDistributionPointBinary).getOctets());
		validity.setOnlyAttributeCerts(issuingDistributionPoint.onlyContainsAttributeCerts());
		validity.setOnlyCaCerts(issuingDistributionPoint.onlyContainsCACerts());
		validity.setOnlyUserCerts(issuingDistributionPoint.onlyContainsUserCerts());
		validity.setIndirectCrl(issuingDistributionPoint.isIndirectCRL());
		validity.setReasonFlags(issuingDistributionPoint.getOnlySomeReasons());
		validity.setUrl(getUrl(issuingDistributionPoint.getDistributionPoint()));
	} else {
		LOG.debug("issuingDistributionPointBinary is null. Issuing Distribution Point fields in CRLValidity cannot be filled.");
	}
}
 
Example #23
Source File: AbstractCRLUtils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
protected void extractExpiredCertsOnCRL(CRLValidity validity, byte[] expiredCertsOnCRLBinaries) {
	if (expiredCertsOnCRLBinaries != null) {
		try {
			ASN1OctetString octetString = (ASN1OctetString) ASN1Primitive.fromByteArray(expiredCertsOnCRLBinaries);
			Time time = Time.getInstance(ASN1Primitive.fromByteArray(octetString.getOctets()));
			if (time != null && time.toASN1Primitive() instanceof ASN1GeneralizedTime) {
				validity.setExpiredCertsOnCRL(time.getDate());
			} else {
				LOG.warn("Attribute 'expiredCertsOnCRL' found but ignored (should be encoded as ASN.1 GeneralizedTime)");
			}
		} catch (Exception e) {
			LOG.error("Unable to parse expiredCertsOnCRL on CRL : {}", e.getMessage(), e);
		}
	}
}
 
Example #24
Source File: ProtectionInfo.java    From InflatableDonkey with MIT License 5 votes vote down vote up
public ProtectionInfo(ASN1Primitive primitive) {
    ASN1Primitive app = DER.asApplicationSpecific(APPLICATION_TAG, primitive);
    DERIterator i = DER.asSequence(app);

    Map<Integer, ASN1Primitive> tagged = i.derTaggedObjects();

    encryptedKeys = new EncryptedKeys(i.next());

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

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

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

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

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

    cont4 = Optional.ofNullable(tagged.get(CONT4))
            .map(DER.as(DEROctetString.class))
            .map(ASN1OctetString::getOctets);
}
 
Example #25
Source File: Asn1Utils.java    From android-testdpc with Apache License 2.0 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(), "UTF-8");
}
 
Example #26
Source File: X509Cert.java    From xipki with Apache License 2.0 5 votes vote down vote up
public byte[] getSubjectKeyId() {
  if (subjectKeyId == null) {
    synchronized (sync) {
      byte[] extnValue = getCoreExtValue(Extension.subjectKeyIdentifier);
      if (extnValue != null) {
        subjectKeyId = ASN1OctetString.getInstance(extnValue).getOctets();
      }
    }
  }

  return subjectKeyId;
}
 
Example #27
Source File: X509Cert.java    From xipki with Apache License 2.0 5 votes vote down vote up
public byte[] getExtensionCoreValue(ASN1ObjectIdentifier extnType) {
  if (bcInstance != null) {
    Extension extn = bcInstance.getExtensions().getExtension(extnType);
    return extn == null ? null : extn.getExtnValue().getOctets();
  } else {
    byte[] rawValue = jceInstance.getExtensionValue(extnType.getId());
    return rawValue == null ? null : ASN1OctetString.getInstance(rawValue).getOctets();
  }
}
 
Example #28
Source File: X509Cert.java    From xipki with Apache License 2.0 5 votes vote down vote up
private byte[] getCoreExtValue(ASN1ObjectIdentifier extnType) {
  if (bcInstance != null) {
    Extensions extns = bcInstance.getExtensions();
    if (extns == null) {
      return null;
    }
    Extension extn = extns.getExtension(extnType);
    return extn == null ? null : extn.getExtnValue().getOctets();
  } else {
    byte[] rawValue = jceInstance.getExtensionValue(extnType.getId());
    return rawValue == null ? null : ASN1OctetString.getInstance(rawValue).getOctets();
  }
}
 
Example #29
Source File: CmpCaClient.java    From xipki with Apache License 2.0 5 votes vote down vote up
private PKIMessage transmit(ProtectedPKIMessage request, String uri) throws Exception {
  byte[] encodedResponse = send(request.toASN1Structure().getEncoded(), uri);
  GeneralPKIMessage response = new GeneralPKIMessage(encodedResponse);

  PKIHeader reqHeader = request.getHeader();
  PKIHeader respHeader = response.getHeader();
  ASN1OctetString tid = reqHeader.getTransactionID();
  if (!tid.equals(respHeader.getTransactionID())) {
    throw new Exception("response.transactionId != request.transactionId");
  }

  ASN1OctetString senderNonce = reqHeader.getSenderNonce();
  if (!senderNonce.equals(respHeader.getRecipNonce())) {
    throw new Exception("response.recipientNonce != request.senderNonce");
  }

  GeneralName rec = respHeader.getRecipient();
  if (!requestorSubject.equals(rec)) {
    throw new Exception("unknown CMP requestor " + rec.toString());
  }

  if (!response.hasProtection()) {
    PKIBody respBody = response.getBody();
    int bodyType = respBody.getType();
    if (bodyType != PKIBody.TYPE_ERROR) {
      throw new Exception("response is not signed");
    } else {
      return response.toASN1Structure();
    }
  }

  if (verifyProtection(response)) {
    return response.toASN1Structure();
  }

  throw new Exception("invalid signature/MAC in PKI protection");
}
 
Example #30
Source File: CtLogVerifyTest.java    From xipki with Apache License 2.0 5 votes vote down vote up
@Test
public void testVerify() throws Exception {
  Security.addProvider(new BouncyCastleProvider());
  byte[] keyBytes = read(pubkeyFile);

  SubjectPublicKeyInfo spki = SubjectPublicKeyInfo.getInstance(X509Util.toDerEncoded(keyBytes));
  byte[] keyId = HashAlgo.SHA256.hash(spki.getEncoded());
  System.out.println("keyId: " + Hex.encode(keyId));

  PublicKey key = KeyUtil.generatePublicKey(spki);
  X509Cert cert = X509Util.parseCert(read(certFile));
  X509Cert caCert = X509Util.parseCert(read(caCertFile));

  // CHECKSTYLE:SKIP
  byte[] issuerKeyHash = HashAlgo.SHA256.hash(caCert.getSubjectPublicKeyInfo().getEncoded());
  // CHECKSTYLE:SKIP
  byte[] preCertTbsCert = CtLog.getPreCertTbsCert(
                            cert.toBcCert().toASN1Structure().getTBSCertificate());

  byte[] extnValue = cert.getExtensionCoreValue(ObjectIdentifiers.Extn.id_SCTs);

  byte[] encodedScts = ASN1OctetString.getInstance(extnValue).getOctets();
  SignedCertificateTimestampList list = SignedCertificateTimestampList.getInstance(encodedScts);
  SerializedSCT sctList = list.getSctList();
  int size = sctList.size();
  Assert.assertEquals("SCT size", 2, size);

  SignedCertificateTimestamp sct = sctList.get(1);
  byte[] logId = sct.getLogId();
  Assert.assertEquals("logId", Hex.encodeUpper(keyId), Hex.encodeUpper(logId));

  Signature sig = Signature.getInstance("SHA256withECDSA");
  sig.initVerify(key);
  CtLog.update(sig, (byte) sct.getVersion(), sct.getTimestamp(),
      sct.getExtensions(), issuerKeyHash, preCertTbsCert);

  boolean sigValid = sig.verify(sct.getDigitallySigned().getSignature());
  Assert.assertEquals("signature valid", true, sigValid);
}