Java Code Examples for org.bouncycastle.asn1.ASN1Sequence#getObjectAt()

The following examples show how to use org.bouncycastle.asn1.ASN1Sequence#getObjectAt() . 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: Attestation.java    From android-testdpc with Apache License 2.0 6 votes vote down vote up
/**
 * Constructs an {@code Attestation} object from the provided {@link X509Certificate},
 * extracting the attestation data from the attestation extension.
 *
 * @throws CertificateParsingException if the certificate does not contain a properly-formatted
 *                                     attestation extension.
 */
@RequiresApi(api = VERSION_CODES.N)
public Attestation(X509Certificate x509Cert) throws CertificateParsingException {
    ASN1Sequence seq = getAttestationSequence(x509Cert);

    attestationVersion = Asn1Utils.getIntegerFromAsn1(seq.getObjectAt(ATTESTATION_VERSION_INDEX));
    attestationSecurityLevel = Asn1Utils.getIntegerFromAsn1(seq.getObjectAt(ATTESTATION_SECURITY_LEVEL_INDEX));
    keymasterVersion = Asn1Utils.getIntegerFromAsn1(seq.getObjectAt(KEYMASTER_VERSION_INDEX));
    keymasterSecurityLevel = Asn1Utils.getIntegerFromAsn1(seq.getObjectAt(KEYMASTER_SECURITY_LEVEL_INDEX));

    attestationChallenge =
            Asn1Utils.getByteArrayFromAsn1(seq.getObjectAt(Attestation.ATTESTATION_CHALLENGE_INDEX));

    uniqueId = Asn1Utils.getByteArrayFromAsn1(seq.getObjectAt(Attestation.UNIQUE_ID_INDEX));

    softwareEnforced = new AuthorizationList(seq.getObjectAt(SW_ENFORCED_INDEX));
    teeEnforced = new AuthorizationList(seq.getObjectAt(TEE_ENFORCED_INDEX));
}
 
Example 2
Source File: ProxyMessage.java    From xipki with Apache License 2.0 6 votes vote down vote up
private NewObjectControl(ASN1Sequence seq) throws BadAsn1ObjectException {
  final int size = seq.size();
  Args.min(size, "seq.size", 1);
  String label = DERUTF8String.getInstance(seq.getObjectAt(0)).getString();
  byte[] id = null;

  for (int i = 1; i < size; i++) {
    ASN1Encodable obj = seq.getObjectAt(i);
    if (obj instanceof ASN1TaggedObject) {
      continue;
    }

    ASN1TaggedObject tagObj = (ASN1TaggedObject) obj;
    int tagNo = tagObj.getTagNo();
    if (tagNo == 0) {
      id = DEROctetString.getInstance(tagObj.getObject()).getOctets();
    }
  }

  this.control = new P11NewKeyControl(id, label);
}
 
Example 3
Source File: Pkcs8Util.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
private static boolean sequenceIsAlgorithmIdentifier(ASN1Sequence sequence) {
	// @formatter:off
	/*
	 * AlgorithmIdentifier ::= ASN1Sequence {
	 * 		algorithm OBJECT IDENTIFIER,
	 * 		parameters ANY DEFINED BY algorithm OPTIONAL
	 * }
	 */
	// @formatter:on

	if ((sequence.size() != 1) && (sequence.size() != 2)) {
		return false;
	}

	Object obj1 = sequence.getObjectAt(0);

	return obj1 instanceof ASN1ObjectIdentifier;

}
 
Example 4
Source File: Attestation.java    From Auditor with MIT License 6 votes vote down vote up
/**
 * Constructs an {@code Attestation} object from the provided {@link X509Certificate},
 * extracting the attestation data from the attestation extension.
 *
 * @throws CertificateParsingException if the certificate does not contain a properly-formatted
 *                                     attestation extension.
 */
public Attestation(X509Certificate x509Cert) throws CertificateParsingException {
    ASN1Sequence seq = getAttestationSequence(x509Cert);

    attestationVersion = Asn1Utils.getIntegerFromAsn1(seq.getObjectAt(ATTESTATION_VERSION_INDEX));
    attestationSecurityLevel = Asn1Utils.getIntegerFromAsn1(seq.getObjectAt(ATTESTATION_SECURITY_LEVEL_INDEX));
    keymasterVersion = Asn1Utils.getIntegerFromAsn1(seq.getObjectAt(KEYMASTER_VERSION_INDEX));
    keymasterSecurityLevel = Asn1Utils.getIntegerFromAsn1(seq.getObjectAt(KEYMASTER_SECURITY_LEVEL_INDEX));

    attestationChallenge =
            Asn1Utils.getByteArrayFromAsn1(seq.getObjectAt(Attestation.ATTESTATION_CHALLENGE_INDEX));

    uniqueId = Asn1Utils.getByteArrayFromAsn1(seq.getObjectAt(Attestation.UNIQUE_ID_INDEX));

    softwareEnforced = new AuthorizationList(seq.getObjectAt(SW_ENFORCED_INDEX));
    teeEnforced = new AuthorizationList(seq.getObjectAt(TEE_ENFORCED_INDEX));
}
 
Example 5
Source File: PdfPKCS7.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Get the "subject" from the TBSCertificate bytes that are passed in
 * @param enc A TBSCertificate in a byte array
 * @return a DERObject
 */
private static ASN1Primitive getSubject(byte[] enc) {
    try {
        ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(enc));
        ASN1Sequence seq = (ASN1Sequence)in.readObject();
        return (ASN1Primitive)seq.getObjectAt(seq.getObjectAt(0) instanceof ASN1TaggedObject ? 5 : 4);
    }
    catch (IOException e) {
        throw new ExceptionConverter(e);
    }
}
 
Example 6
Source File: Spkac.java    From keystore-explorer with 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 7
Source File: X509Ext.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
private String getMsCertificateTemplateStringValue(byte[] octets) {

		// @formatter:off

		/*
			CertificateTemplate ::= SEQUENCE
			{
				templateID              EncodedObjectID,
				templateMajorVersion    TemplateVersion,
				templateMinorVersion    TemplateVersion OPTIONAL
			}
			TemplateVersion ::= INTEGER (0..4294967295)
		 */

		// @formatter:on

		ASN1Sequence asn1Sequence = ASN1Sequence.getInstance(octets);
		ASN1ObjectIdentifier templateID = (ASN1ObjectIdentifier) asn1Sequence.getObjectAt(0);
		ASN1Integer majorVersion = (ASN1Integer) asn1Sequence.getObjectAt(1);
		ASN1Integer minorVersion = (ASN1Integer) asn1Sequence.getObjectAt(2);

		StringBuilder sb = new StringBuilder();

		sb.append(MessageFormat.format(res.getString("MSCertificateTemplate.ID"), templateID.getId()));
		sb.append(NEWLINE);

		sb.append(MessageFormat.format(res.getString("MSCertificateTemplate.MajorVersion"), majorVersion));
		sb.append(NEWLINE);

		if (minorVersion != null) {
			sb.append(MessageFormat.format(res.getString("MSCertificateTemplate.MinorVersion"), minorVersion));
			sb.append(NEWLINE);
		}

		return sb.toString();
	}
 
Example 8
Source File: ProxyMessage.java    From xipki with Apache License 2.0 5 votes vote down vote up
private RemoveObjectsParams(ASN1Sequence seq) throws BadAsn1ObjectException {
  requireRange(seq, 2, 3);
  int idx = 0;
  slotId = SlotIdentifier.getInstance(seq.getObjectAt(idx++)).getValue();
  final int size = seq.size();
  ASN1Encodable asn1Id = null;
  ASN1Encodable asn1Label = null;
  if (size == 2) {
    ASN1Encodable asn1 = seq.getObjectAt(1);
    if (asn1 instanceof ASN1String) {
      asn1Label = asn1;
    } else {
      asn1Id = asn1;
    }
  } else {
    asn1Id = seq.getObjectAt(idx++);
    asn1Label = seq.getObjectAt(idx++);
  }

  objectId = (asn1Id == null) ? null : getOctetStringBytes(asn1Id);
  objectLabel = (asn1Label == null) ? null : getUtf8String(seq.getObjectAt(idx++));

  if ((objectId == null || objectId.length == 0) && StringUtil.isBlank(objectLabel)) {
    throw new BadAsn1ObjectException("invalid object RemoveObjectsParams: "
        + "at least one of id and label must not be null");
  }
}
 
Example 9
Source File: SubjectChecker.java    From xipki with Apache License 2.0 5 votes vote down vote up
private static String getRdnTextValueOfRequest(RDN requestedRdn)
    throws BadCertTemplateException {
  ASN1ObjectIdentifier type = requestedRdn.getFirst().getType();
  ASN1Encodable vec = requestedRdn.getFirst().getValue();
  if (ObjectIdentifiers.DN.dateOfBirth.equals(type)) {
    if (!(vec instanceof ASN1GeneralizedTime)) {
      throw new BadCertTemplateException("requested RDN is not of GeneralizedTime");
    }
    return ((ASN1GeneralizedTime) vec).getTimeString();
  } else if (ObjectIdentifiers.DN.postalAddress.equals(type)) {
    if (!(vec instanceof ASN1Sequence)) {
      throw new BadCertTemplateException("requested RDN is not of Sequence");
    }

    ASN1Sequence seq = (ASN1Sequence) vec;
    final int n = seq.size();

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < n; i++) {
      ASN1Encodable obj = seq.getObjectAt(i);
      String textValue = X509Util.rdnValueToString(obj);
      sb.append("[").append(i).append("]=").append(textValue).append(",");
    }

    return sb.toString();
  } else {
    return X509Util.rdnValueToString(vec);
  }
}
 
Example 10
Source File: PdfPKCS7.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Get the "issuer" from the TBSCertificate bytes that are passed in
 * @param enc a TBSCertificate in a byte array
 * @return a DERObject
 */
private static ASN1Primitive getIssuer(byte[] enc) {
    try {
        ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(enc));
        ASN1Sequence seq = (ASN1Sequence)in.readObject();
        return (ASN1Primitive)seq.getObjectAt(seq.getObjectAt(0) instanceof ASN1TaggedObject ? 3 : 2);
    }
    catch (IOException e) {
        throw new ExceptionConverter(e);
    }
}
 
Example 11
Source File: DSSSignatureUtils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Converts an ASN.1 value to a XML Signature Value.
 *
 * The JAVA JCE ECDSA/DSA Signature algorithm creates ASN.1 encoded (r,s) value pairs; the XML Signature requires
 * the
 * core BigInteger values.
 *
 * @param binaries
 *            the ASN1 signature value
 * @return the decode bytes
 * @throws IOException
 * @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A>
 * @see <A HREF="ftp://ftp.rfc-editor.org/in-notes/rfc4050.txt">3.3. ECDSA Signatures</A>
 */
private static byte[] convertASN1toXMLDSIG(byte[] binaries) {

	try (ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ASN1InputStream is = new ASN1InputStream(binaries)) {

		ASN1Sequence seq = (ASN1Sequence) is.readObject();
		if (seq.size() != 2) {
			throw new IllegalArgumentException("ASN1 Sequence size should be 2 !");
		}

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

		byte[] rBytes = BigIntegers.asUnsignedByteArray(r.getValue());
		int rSize = rBytes.length;
		byte[] sBytes = BigIntegers.asUnsignedByteArray(s.getValue());
		int sSize = sBytes.length;
		int max = Math.max(rSize, sSize);
		max = max % 2 == 0 ? max : max + 1;
		leftPad(buffer, max, rBytes);
		buffer.write(rBytes);
		leftPad(buffer, max, sBytes);
		buffer.write(sBytes);

		return buffer.toByteArray();
	} catch (Exception e) {
		throw new DSSException("Unable to convert to xmlDsig : " + e.getMessage(), e);
	}
}
 
Example 12
Source File: X509Ext.java    From portecle with 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 13
Source File: DSSASN1Utils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Get the list of all QCType Ids that are present in the certificate.
 * (As per ETSI EN 319 412-5 V2.1.1)
 * 
 * @param certToken
 *            the certificate
 * @return the list of QCTypes oids
 */
public static List<String> getQCTypesIdList(final CertificateToken certToken) {
	final List<String> qcTypesIdList = 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_TYPE_STATEMENT_OID.equals(statement.getStatementId().getId())) {
					final ASN1Encodable qcTypeInfo1 = statement.getStatementInfo();
					if (qcTypeInfo1 instanceof ASN1Sequence) {
						final ASN1Sequence qcTypeInfo = (ASN1Sequence) qcTypeInfo1;
						for (int jj = 0; jj < qcTypeInfo.size(); jj++) {
							final ASN1Encodable e1 = qcTypeInfo.getObjectAt(jj);
							if (e1 instanceof ASN1ObjectIdentifier) {
								final ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) e1;
								qcTypesIdList.add(oid.getId());
							} else {
								LOG.warn("ASN1Sequence in QcTypes does not contain ASN1ObjectIdentifer, but {}",
										e1.getClass().getName());
							}
						}
					} else {
						LOG.warn("QcTypes not an ASN1Sequence, but {}", qcTypeInfo1.getClass().getName());
					}
				}
			}
		} catch (Exception e) {
			LOG.warn("Unable to parse the qCStatements extension '{}' : {}", Utils.toBase64(qcStatement), e.getMessage(), e);
		}
	}

	return qcTypesIdList;
}
 
Example 14
Source File: OpenSslPvkUtil.java    From keystore-explorer with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Detect if a OpenSSL private key is encrypted or not.
 *
 * @param openSsl BA data containing OpenSSL private key
 * @return Encryption type or null if not a valid OpenSSL private key
 * @throws IOException
 *             If an I/O problem occurred
 */
public static EncryptionType getEncryptionType(byte[] openSsl) throws IOException {

	// In PEM format?
	PemInfo pemInfo = PemUtil.decode(openSsl);

	if (pemInfo != null) {
		String pemType = pemInfo.getType();

		// PEM type of OpenSSL?
		if (OPENSSL_RSA_PVK_PEM_TYPE.equals(pemType) || OPENSSL_DSA_PVK_PEM_TYPE.equals(pemType)
				|| OPENSSL_EC_PVK_PEM_TYPE.equals(pemType)) {

			// Encrypted? It is if PEM contains appropriate header attributes/values
			PemAttributes pemAttributes = pemInfo.getAttributes();

			if ((pemAttributes != null) && (pemAttributes.get(PROC_TYPE_ATTR_NAME) != null)
					&& (pemAttributes.get(PROC_TYPE_ATTR_NAME).getValue().equals(PROC_TYPE_ATTR_VALUE))
					&& (pemAttributes.get(DEK_INFO_ATTR_NAME) != null)) {
				return ENCRYPTED;
			} else {
				return UNENCRYPTED;
			}
		}
	}

	// In ASN.1 format?
	try {
		// If OpenSSL will be a sequence of 9 (RSA) or 6 (DSA) integers or 2-4 mixed elements (EC)
		ASN1Primitive key = ASN1Primitive.fromByteArray(openSsl);

		if (key instanceof ASN1Sequence) {
			ASN1Sequence seq = (ASN1Sequence) key;

			// handle EC structure first (RFC 5915)
			//   ECPrivateKey ::= SEQUENCE {
			//	     version        INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1),
			//	     privateKey     OCTET STRING,
			//	     parameters [0] ECParameters {{ NamedCurve }} OPTIONAL,
			//	     publicKey  [1] BIT STRING OPTIONAL
			//	   }
			if ((seq.size() >= 2) && (seq.size() <= 4) && seq.getObjectAt(0) instanceof ASN1Integer) {
				BigInteger version = ((ASN1Integer) seq.getObjectAt(0)).getValue();
				if (version.equals(VERSION_EC)) {
					if (seq.getObjectAt(1) instanceof ASN1OctetString) {
						return UNENCRYPTED; // ASN.1 OpenSSL is always unencrypted
					} else {
						return null; // Not OpenSSL
					}
				}
			}

			for (int i = 0; i < seq.size(); i++) {
				if (!(seq.getObjectAt(i) instanceof ASN1Integer)) {
					return null; // Not OpenSSL
				}
			}

			if ((seq.size() == 9) || (seq.size() == 6)) {
				return UNENCRYPTED; // ASN.1 OpenSSL is always unencrypted
			}
		}
	} catch (IOException ex) {
		return null; // Not an OpenSSL file
	}

	return null; // Not an OpenSSL file
}
 
Example 15
Source File: CAdESSignature.java    From dss with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public SignatureProductionPlace getSignatureProductionPlace() {
	Attribute signatureProductionPlaceAttr = getSignedAttribute(PKCSObjectIdentifiers.id_aa_ets_signerLocation);
	if (signatureProductionPlaceAttr == null) {
		return null;
	}

	final ASN1Encodable asn1Encodable = signatureProductionPlaceAttr.getAttrValues().getObjectAt(0);
	SignerLocation signerLocation = null;
	try {
		signerLocation = SignerLocation.getInstance(asn1Encodable);
	} catch (Exception e) {
		LOG.error(e.getMessage(), e);
	}
	if (signerLocation == null) {
		return null;
	}
	final SignatureProductionPlace signatureProductionPlace = new SignatureProductionPlace();
	final DirectoryString countryName = signerLocation.getCountry();
	if (countryName != null) {
		signatureProductionPlace.setCountryName(countryName.getString());
	}
	final DirectoryString localityName = signerLocation.getLocality();
	if (localityName != null) {
		signatureProductionPlace.setCity(localityName.getString());
	}
	final StringBuilder address = new StringBuilder();
	final ASN1Sequence seq = signerLocation.getPostalAddress();
	if (seq != null) {

		for (int ii = 0; ii < seq.size(); ii++) {

			if (seq.getObjectAt(ii) instanceof DEROctetString) {
				if (address.length() > 0) {
					address.append(" / ");
				}
				// TODO: getOctets returns an array
				address.append(new String(((DEROctetString) seq.getObjectAt(ii)).getOctets()));
			} else if (seq.getObjectAt(ii) instanceof DERUTF8String) {

				if (address.length() > 0) {
					address.append(" / ");
				}
				final DERUTF8String derutf8String = (DERUTF8String) seq.getObjectAt(ii);
				address.append(derutf8String.getString());
			}
		}
	}
	signatureProductionPlace.setStreetAddress(address.toString());
	// This property is not used in CAdES version of signature
	// signatureProductionPlace.setStateOrProvince(stateOrProvince);
	return signatureProductionPlace;
}
 
Example 16
Source File: EccUtilTest.java    From keystore-explorer with GNU General Public License v3.0 4 votes vote down vote up
@ParameterizedTest
@ValueSource(strings = {
	// SEC curves
	"secp112r1", "secp112r2", "secp128r1", "secp128r2", "secp160k1", "secp160r1", "secp160r2", "secp192k1",
	/* "secp192r1", = prime192v1 */ "secp224k1", "secp224r1", "secp256k1", /* "secp256r1", = prime256v1 */
	"secp384r1", "secp521r1", "sect113r1", "sect113r2", "sect131r1", "sect131r2", "sect163k1", "sect163r1",
	"sect163r2", "sect193r1", "sect193r2", "sect233k1", "sect233r1", "sect239k1", "sect283k1", "sect283r1",
	"sect409k1", "sect409r1", "sect571k1", "sect571r1",
	// ANSI X9.62 curves
	"prime192v1", "prime192v2", "prime192v3", "prime239v1", "prime239v2", "prime239v3", "prime256v1", "c2pnb163v1",
	"c2pnb163v2", "c2pnb163v3", "c2pnb176w1", "c2tnb191v1", "c2tnb191v2", "c2tnb191v3", "c2tnb239v1", "c2tnb239v2",
	"c2tnb239v3", "c2tnb359v1", "c2tnb431r1", "c2pnb208w1", "c2pnb272w1", "c2pnb304w1", "c2pnb368w1",
	// Brainpool curves
	"brainpoolP160r1", "brainpoolP160t1", "brainpoolP192r1", "brainpoolP192t1", "brainpoolP224r1", "brainpoolP224t1",
	"brainpoolP256r1", "brainpoolP256t1", "brainpoolP320r1", "brainpoolP320t1", "brainpoolP384r1", "brainpoolP384t1",
	"brainpoolP512r1", "brainpoolP512t1"
	// NIST curves are a subset of SEC curves (not explicitly tested here)
})
public void convertToECPrivateKeyStructure(String curveName) throws Exception {

	KeyPair keyPair = KeyPairUtil.generateECKeyPair(curveName, BC);
	ECPrivateKey ecPrivateKey = (ECPrivateKey) keyPair.getPrivate();

	byte[] encoded = EccUtil.convertToECPrivateKeyStructure(ecPrivateKey).toASN1Primitive().getEncoded();

	// verify ASN.1 structure "ECPrivateKey" from RFC 5915:
	//
	// ECPrivateKey ::= SEQUENCE {
    //    version        INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1),
    //    privateKey     OCTET STRING,
    //    parameters [0] ECParameters {{ NamedCurve }} OPTIONAL,
    //    publicKey  [1] BIT STRING OPTIONAL
    // }
	//
    // ECParameters ::= CHOICE {
    //     namedCurve         OBJECT IDENTIFIER
    //     -- implicitCurve   NULL
    //     -- specifiedCurve  SpecifiedECDomain
    //   }
	// RFC 5480:
    // -- implicitCurve and specifiedCurve MUST NOT be used in PKIX.

	ASN1Sequence sequence = ASN1Sequence.getInstance(encoded);

	// check version of data structure
	BigInteger version = ((ASN1Integer) sequence.getObjectAt(0)).getValue();
	assertThat(version).isEqualTo(BigInteger.ONE);

	// next is an octet string with the key
	assertThat(sequence.getObjectAt(1)).isInstanceOf(ASN1OctetString.class);

	// check for existence of (optional) EC parameters
	ASN1Encodable tagged0 = sequence.getObjectAt(2);
	DLTaggedObject derTaggedObject = (DLTaggedObject) tagged0;
	assertThat(derTaggedObject.getTagNo()).isEqualTo(0);

	// check that EC parameters contain the right curve name
	ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) derTaggedObject.getObject();
	String resolvedCurveName = ObjectIdUtil.toString(oid);
	assertThat(resolvedCurveName).containsIgnoringCase(curveName);
}
 
Example 17
Source File: X509Ext.java    From portecle with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Get Novell Security Attributes (2.16.840.1.113719.1.9.4.1) extension value as a string.
 *
 * @see <a href="https://www.novell.com/documentation/developer/ncslib/npki_enu/data/a2uetmm.html">Novell Security
 *      Attributes Extension</a>
 * @param bValue The octet string value
 * @return Extension value as a string
 * @throws IOException If an I/O problem occurs
 */
private String getNovellSecurityAttributesStringValue(byte[] bValue)
    throws IOException
{
	// TODO...

	ASN1Sequence attrs = (ASN1Sequence) ASN1Primitive.fromByteArray(bValue);
	StringBuilder sb = new StringBuilder();

	// "Novell Security Attribute(tm)"
	String sTM = ((ASN1String) attrs.getObjectAt(2)).getString();
	sb.append(escapeHtml(sTM));
	sb.append("<br>");

	// OCTET STRING of size 2, 1st is major version, 2nd is minor version
	byte[] bVer = ((DEROctetString) attrs.getObjectAt(0)).getOctets();
	sb.append("Major version: ").append(Byte.toString(bVer[0]));
	sb.append(", minor version: ").append(Byte.toString(bVer[1]));
	sb.append("<br>");

	// Nonverified Subscriber Information
	boolean bNSI = ((ASN1Boolean) attrs.getObjectAt(1)).isTrue();
	sb.append("Nonverified Subscriber Information: ").append(bNSI);
	sb.append("<br>");

	// URI reference
	String sUri = ((ASN1String) attrs.getObjectAt(3)).getString();
	sb.append("URI: ");
	sb.append(getLink(sUri, escapeHtml(sUri), LinkClass.BROWSER));

	// GLB Extensions (GLB ~ "Greatest Lower Bound")

	sb.append("<ul>");
	ASN1Sequence glbs = (ASN1Sequence) attrs.getObjectAt(4);
	sb.append("<li>GLB extensions:<ul>");

	/*
	 * TODO: verify that we can do getObjectAt(n) or if we need to examine tag numbers of the tagged objects
	 */

	// Key quality
	ASN1Sequence keyq = (ASN1Sequence) ((ASN1TaggedObject) glbs.getObjectAt(0)).getObject();
	sb.append("<li>").append(RB.getString("NovellKeyQuality"));
	sb.append("<ul>").append(getNovellQualityAttr(keyq)).append("</ul></li>");

	// Crypto process quality
	ASN1Sequence cpq = (ASN1Sequence) ((ASN1TaggedObject) glbs.getObjectAt(1)).getObject();
	sb.append("<li>").append(RB.getString("NovellCryptoProcessQuality"));
	sb.append("<ul>").append(getNovellQualityAttr(cpq)).append("</ul></li>");

	// Certificate class
	ASN1Sequence cclass = (ASN1Sequence) ((ASN1TaggedObject) glbs.getObjectAt(2)).getObject();
	sb.append("<li>").append(RB.getString("NovellCertClass"));
	sb.append(": ");
	BigInteger sv = ((ASN1Integer) cclass.getObjectAt(0)).getValue();
	String sc = getRes("NovellCertClass." + sv, "UnregocnisedNovellCertClass");
	sb.append(MessageFormat.format(sc, sv));
	sb.append("</li>");

	boolean valid = true;
	if (cclass.size() > 1)
	{
		valid = ((ASN1Boolean) cclass.getObjectAt(1)).isTrue();
	}
	sb.append("<li>");
	sb.append(RB.getString("NovellCertClassValid." + valid));
	sb.append("</li></ul>");

	// Enterprise ID
	/*
	 * ASN1Sequence eid = (ASN1Sequence) ((ASN1TaggedObject) glbs.getObjectAt(3)).getObject(); ASN1Sequence
	 * rootLabel = (ASN1Sequence) ((ASN1TaggedObject) eid.getObjectAt(0)).getObject(); ASN1Sequence registryLabel =
	 * (ASN1Sequence) ((ASN1TaggedObject) eid.getObjectAt(1)).getObject(); ASN1Sequence eLabels = (ASN1Sequence)
	 * ((ASN1TaggedObject) eid.getObjectAt(2)).getObject(); for (int i = 0, len = eLabels.size(); i < len; i++) { //
	 * Hmm... I thought this would be a sequence of sequences, // but the following throws a ClassCastException...?
	 * // ASN1Sequence eLabel = (ASN1Sequence) eLabels.getObjectAt(i); }
	 */
	sb.append(RB.getString("NovellEnterpriseID"));
	sb.append(' ').append(RB.getString("DecodeNotImplemented")); // TODO

	return sb.toString();
}
 
Example 18
Source File: X509Ext.java    From portecle with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Get Policy Mappings (2.5.29.33) extension value as a string.
 *
 * <pre>
 * PolicyMappings ::= SEQUENCE SIZE (1..MAX) OF SEQUENCE {
 *     issuerDomainPolicy      CertPolicyId,
 *      subjectDomainPolicy     CertPolicyId }
 * CertPolicyId ::= OBJECT IDENTIFIER
 * </pre>
 *
 * @param bValue The octet string value
 * @return Extension value as a string
 * @throws IOException If an I/O problem occurs
 */
private String getPolicyMappingsStringValue(byte[] bValue)
    throws IOException
{
	// Get sequence of policy mappings
	ASN1Sequence policyMappings = (ASN1Sequence) ASN1Primitive.fromByteArray(bValue);

	StringBuilder strBuff = new StringBuilder("<ul>");

	// Get each policy mapping
	for (int i = 0, len = policyMappings.size(); i < len; i++)
	{
		ASN1Sequence policyMapping = (ASN1Sequence) policyMappings.getObjectAt(i);
		int pmLen = policyMapping.size();

		strBuff.append("<li>");
		strBuff.append(MessageFormat.format(RB.getString("PolicyMapping"), i + 1));

		if (pmLen > 0)
		{
			ASN1ObjectIdentifier issuerDomainPolicy = (ASN1ObjectIdentifier) policyMapping.getObjectAt(0);

			strBuff.append("<ul><li>");
			strBuff.append(MessageFormat.format(RB.getString("IssuerDomainPolicy"), issuerDomainPolicy.getId()));
			strBuff.append("</li></ul>");
		}

		if (pmLen > 1)
		{
			ASN1ObjectIdentifier subjectDomainPolicy = (ASN1ObjectIdentifier) policyMapping.getObjectAt(1);

			strBuff.append("<ul><li>");
			strBuff.append(MessageFormat.format(RB.getString("SubjectDomainPolicy"), subjectDomainPolicy.getId()));
			strBuff.append("</li></ul>");
		}

		strBuff.append("</li>");
	}
	strBuff.append("</ul>");

	return strBuff.toString();
}
 
Example 19
Source File: SubjectChecker.java    From xipki with Apache License 2.0 4 votes vote down vote up
private static String getAtvValueString(String name, AttributeTypeAndValue atv,
    StringType stringType, StringBuilder failureMsg) {
  ASN1ObjectIdentifier type = atv.getType();
  ASN1Encodable atvValue = atv.getValue();

  if (ObjectIdentifiers.DN.dateOfBirth.equals(type)) {
    if (!(atvValue instanceof ASN1GeneralizedTime)) {
      failureMsg.append(name).append(" is not of type GeneralizedTime; ");
      return null;
    }
    return ((ASN1GeneralizedTime) atvValue).getTimeString();
  } else if (ObjectIdentifiers.DN.postalAddress.equals(type)) {
    if (!(atvValue instanceof ASN1Sequence)) {
      failureMsg.append(name).append(" is not of type Sequence; ");
      return null;
    }

    ASN1Sequence seq = (ASN1Sequence) atvValue;
    final int n = seq.size();

    StringBuilder sb = new StringBuilder();
    boolean validEncoding = true;
    for (int i = 0; i < n; i++) {
      ASN1Encodable obj = seq.getObjectAt(i);
      if (!matchStringType(obj, stringType)) {
        failureMsg.append(name).append(".[").append(i).append("] is not of type ")
          .append(stringType.name()).append("; ");
        validEncoding = false;
        break;
      }

      String textValue = X509Util.rdnValueToString(obj);
      sb.append("[").append(i).append("]=").append(textValue).append(",");
    }

    if (!validEncoding) {
      return null;
    }

    return sb.toString();
  } else {
    if (!matchStringType(atvValue, stringType)) {
      failureMsg.append(name).append(" is not of type " + stringType.name()).append("; ");
      return null;
    }

    return X509Util.rdnValueToString(atvValue);
  }
}
 
Example 20
Source File: Pkcs8Util.java    From keystore-explorer with GNU General Public License v3.0 4 votes vote down vote up
private static String getPrivateKeyAlgorithm(byte[] unencPkcs8) throws IOException, CryptoException {
	// @formatter:off
	/*
	 * Get private key algorithm from unencrypted PKCS #8 bytes:
	 *
	 * PrivateKeyInfo ::= ASN1Sequence {
	 * 		version Version,
	 * 		privateKeyAlgorithm PrivateKeyAlgorithmIdentifier, privateKey
	 * 		PrivateKey, attributes [0] IMPLICIT Attributes OPTIONAL
	 * }
	 *
	 * PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier
	 *
	 * AlgorithmIdentifier ::= ASN1Sequence {
	 * 		algorithm OBJECT IDENTIFIER,
	 * 		parameters ANY DEFINED BY algorithm OPTIONAL
	 * }
	 */
	// @formatter:on

	try (ASN1InputStream ais = new ASN1InputStream(new ByteArrayInputStream(unencPkcs8))) {

		ASN1Encodable derEnc;
		try {
			derEnc = ais.readObject();
		} catch (OutOfMemoryError err) { // Happens with some non ASN.1 files
			throw new CryptoException(res.getString("NoUnencryptedPkcs8.exception.message"));
		}

		if (!(derEnc instanceof ASN1Sequence)) {
			throw new CryptoException(res.getString("NoUnencryptedPkcs8.exception.message"));
		}

		ASN1Sequence privateKeyInfoSequence = (ASN1Sequence) derEnc;

		derEnc = privateKeyInfoSequence.getObjectAt(1);

		if (!(derEnc instanceof ASN1Sequence)) {
			throw new CryptoException(res.getString("NoUnencryptedPkcs8.exception.message"));
		}

		ASN1Sequence privateKeyAlgorithmSequence = (ASN1Sequence) derEnc;

		derEnc = privateKeyAlgorithmSequence.getObjectAt(0);

		if (!(derEnc instanceof ASN1ObjectIdentifier)) {
			throw new CryptoException(res.getString("NoUnencryptedPkcs8.exception.message"));
		}

		ASN1ObjectIdentifier algorithmOid = (ASN1ObjectIdentifier) derEnc;

		String oid = algorithmOid.getId();

		if (oid.equals(RSA.oid())) {
			return RSA.jce();
		} else if (oid.equals(DSA.oid())) {
			return DSA.jce();
		} else {
			return oid; // Unknown algorithm
		}
	}
}