use of org.openecard.bouncycastle.asn1.ASN1Set in project android_frameworks_base by ResurrectionRemix.
the class ESTHandler method buildCSR.
private byte[] buildCSR(ByteBuffer octetBuffer, OMADMAdapter omadmAdapter, HTTPHandler httpHandler) throws IOException, GeneralSecurityException {
//Security.addProvider(new BouncyCastleProvider());
Log.d(TAG, "/csrattrs:");
/*
byte[] octets = new byte[octetBuffer.remaining()];
octetBuffer.duplicate().get(octets);
for (byte b : octets) {
System.out.printf("%02x ", b & 0xff);
}
*/
Collection<Asn1Object> csrs = Asn1Decoder.decode(octetBuffer);
for (Asn1Object asn1Object : csrs) {
Log.d(TAG, asn1Object.toString());
}
if (csrs.size() != 1) {
throw new IOException("Unexpected object count in CSR attributes response: " + csrs.size());
}
Asn1Object sequence = csrs.iterator().next();
if (sequence.getClass() != Asn1Constructed.class) {
throw new IOException("Unexpected CSR attribute container: " + sequence);
}
String keyAlgo = null;
Asn1Oid keyAlgoOID = null;
String sigAlgo = null;
String curveName = null;
Asn1Oid pubCrypto = null;
int keySize = -1;
Map<Asn1Oid, ASN1Encodable> idAttributes = new HashMap<>();
for (Asn1Object child : sequence.getChildren()) {
if (child.getTag() == Asn1Decoder.TAG_OID) {
Asn1Oid oid = (Asn1Oid) child;
OidMappings.SigEntry sigEntry = OidMappings.getSigEntry(oid);
if (sigEntry != null) {
sigAlgo = sigEntry.getSigAlgo();
keyAlgoOID = sigEntry.getKeyAlgo();
keyAlgo = OidMappings.getJCEName(keyAlgoOID);
} else if (oid.equals(OidMappings.sPkcs9AtChallengePassword)) {
byte[] tlsUnique = httpHandler.getTLSUnique();
if (tlsUnique != null) {
idAttributes.put(oid, new DERPrintableString(Base64.encodeToString(tlsUnique, Base64.DEFAULT)));
} else {
Log.w(TAG, "Cannot retrieve TLS unique channel binding");
}
}
} else if (child.getTag() == Asn1Decoder.TAG_SEQ) {
Asn1Oid oid = null;
Set<Asn1Oid> oidValues = new HashSet<>();
List<Asn1Object> values = new ArrayList<>();
for (Asn1Object attributeSeq : child.getChildren()) {
if (attributeSeq.getTag() == Asn1Decoder.TAG_OID) {
oid = (Asn1Oid) attributeSeq;
} else if (attributeSeq.getTag() == Asn1Decoder.TAG_SET) {
for (Asn1Object value : attributeSeq.getChildren()) {
if (value.getTag() == Asn1Decoder.TAG_OID) {
oidValues.add((Asn1Oid) value);
} else {
values.add(value);
}
}
}
}
if (oid == null) {
throw new IOException("Invalid attribute, no OID");
}
if (oid.equals(OidMappings.sExtensionRequest)) {
for (Asn1Oid subOid : oidValues) {
if (OidMappings.isIDAttribute(subOid)) {
if (subOid.equals(OidMappings.sMAC)) {
idAttributes.put(subOid, new DERIA5String(omadmAdapter.getMAC()));
} else if (subOid.equals(OidMappings.sIMEI)) {
idAttributes.put(subOid, new DERIA5String(omadmAdapter.getImei()));
} else if (subOid.equals(OidMappings.sMEID)) {
idAttributes.put(subOid, new DERBitString(omadmAdapter.getMeid()));
} else if (subOid.equals(OidMappings.sDevID)) {
idAttributes.put(subOid, new DERPrintableString(omadmAdapter.getDevID()));
}
}
}
} else if (OidMappings.getCryptoID(oid) != null) {
pubCrypto = oid;
if (!values.isEmpty()) {
for (Asn1Object value : values) {
if (value.getTag() == Asn1Decoder.TAG_INTEGER) {
keySize = (int) ((Asn1Integer) value).getValue();
}
}
}
if (oid.equals(OidMappings.sAlgo_EC)) {
if (oidValues.isEmpty()) {
throw new IOException("No ECC curve name provided");
}
for (Asn1Oid value : oidValues) {
curveName = OidMappings.getJCEName(value);
if (curveName != null) {
break;
}
}
if (curveName == null) {
throw new IOException("Found no ECC curve for " + oidValues);
}
}
}
}
}
if (keyAlgoOID == null) {
throw new IOException("No public key algorithm specified");
}
if (pubCrypto != null && !pubCrypto.equals(keyAlgoOID)) {
throw new IOException("Mismatching key algorithms");
}
if (keyAlgoOID.equals(OidMappings.sAlgo_RSA)) {
if (keySize < MinRSAKeySize) {
if (keySize >= 0) {
Log.i(TAG, "Upgrading suggested RSA key size from " + keySize + " to " + MinRSAKeySize);
}
keySize = MinRSAKeySize;
}
}
Log.d(TAG, String.format("pub key '%s', signature '%s', ECC curve '%s', id-atts %s", keyAlgo, sigAlgo, curveName, idAttributes));
/*
Ruckus:
SEQUENCE:
OID=1.2.840.113549.1.1.11 (algo_id_sha256WithRSAEncryption)
RFC-7030:
SEQUENCE:
OID=1.2.840.113549.1.9.7 (challengePassword)
SEQUENCE:
OID=1.2.840.10045.2.1 (algo_id_ecPublicKey)
SET:
OID=1.3.132.0.34 (secp384r1)
SEQUENCE:
OID=1.2.840.113549.1.9.14 (extensionRequest)
SET:
OID=1.3.6.1.1.1.1.22 (mac-address)
OID=1.2.840.10045.4.3.3 (eccdaWithSHA384)
1L, 3L, 6L, 1L, 1L, 1L, 1L, 22
*/
// ECC Does not appear to be supported currently
KeyPairGenerator kpg = KeyPairGenerator.getInstance(keyAlgo);
if (curveName != null) {
AlgorithmParameters algorithmParameters = AlgorithmParameters.getInstance(keyAlgo);
algorithmParameters.init(new ECNamedCurveGenParameterSpec(curveName));
kpg.initialize(algorithmParameters.getParameterSpec(ECNamedCurveGenParameterSpec.class));
} else {
kpg.initialize(keySize);
}
KeyPair kp = kpg.generateKeyPair();
X500Principal subject = new X500Principal("CN=Android, O=Google, C=US");
mClientKey = kp.getPrivate();
// !!! Map the idAttributes into an ASN1Set of values to pass to
// the PKCS10CertificationRequest - this code is using outdated BC classes and
// has *not* been tested.
ASN1Set attributes;
if (!idAttributes.isEmpty()) {
ASN1EncodableVector payload = new DEREncodableVector();
for (Map.Entry<Asn1Oid, ASN1Encodable> entry : idAttributes.entrySet()) {
DERObjectIdentifier type = new DERObjectIdentifier(entry.getKey().toOIDString());
ASN1Set values = new DERSet(entry.getValue());
Attribute attribute = new Attribute(type, values);
payload.add(attribute);
}
attributes = new DERSet(payload);
} else {
attributes = null;
}
return new PKCS10CertificationRequest(sigAlgo, subject, kp.getPublic(), attributes, mClientKey).getEncoded();
}
use of org.openecard.bouncycastle.asn1.ASN1Set in project nhin-d by DirectProject.
the class CertGenerator method createCertFromCSR.
public static X509Certificate createCertFromCSR(PKCS10CertificationRequest certReq, CertCreateFields signerCert) throws Exception {
certReq.verify();
final CertificationRequestInfo reqInfo = certReq.getCertificationRequestInfo();
final X509V3CertificateGenerator v1CertGen = new X509V3CertificateGenerator();
final Calendar start = Calendar.getInstance();
final Calendar end = Calendar.getInstance();
end.add(Calendar.YEAR, 3);
v1CertGen.setSerialNumber(BigInteger.valueOf(generatePositiveRandom()));
// issuer is the parent cert
v1CertGen.setIssuerDN(signerCert.getSignerCert().getSubjectX500Principal());
v1CertGen.setNotBefore(start.getTime());
v1CertGen.setNotAfter(end.getTime());
v1CertGen.setSubjectDN(new X509Principal(reqInfo.getSubject().toString()));
v1CertGen.setPublicKey(certReq.getPublicKey());
v1CertGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
final ASN1Set attributesAsn1Set = reqInfo.getAttributes();
X509Extensions certificateRequestExtensions = null;
for (int i = 0; i < attributesAsn1Set.size(); ++i) {
// There should be only only one attribute in the set. (that is, only
// the `Extension Request`, but loop through to find it properly)
final DEREncodable derEncodable = attributesAsn1Set.getObjectAt(i);
if (derEncodable instanceof DERSequence) {
final Attribute attribute = new Attribute((DERSequence) attributesAsn1Set.getObjectAt(i));
if (attribute.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
// The `Extension Request` attribute is present.
final ASN1Set attributeValues = attribute.getAttrValues();
// Assume that it is the first value of the set.
if (attributeValues.size() >= 1) {
certificateRequestExtensions = new X509Extensions((ASN1Sequence) attributeValues.getObjectAt(0));
// No need to search any more.
//break;
}
}
}
}
@SuppressWarnings("unchecked") Enumeration<DERObjectIdentifier> oids = certificateRequestExtensions.oids();
while (oids.hasMoreElements()) {
DERObjectIdentifier oid = oids.nextElement();
X509Extension ex = certificateRequestExtensions.getExtension(oid);
v1CertGen.addExtension(oid, ex.isCritical(), X509Extension.convertValueToObject(ex));
}
return v1CertGen.generate((PrivateKey) signerCert.getSignerKey(), CryptoExtensions.getJCEProviderName());
}
use of org.openecard.bouncycastle.asn1.ASN1Set in project robovm by robovm.
the class CMSSignedDataGenerator method generate.
public CMSSignedData generate(// FIXME Avoid accessing more than once to support CMSProcessableInputStream
CMSTypedData content, boolean encapsulate) throws CMSException {
if (!signerInfs.isEmpty()) {
throw new IllegalStateException("this method can only be used with SignerInfoGenerator");
}
// TODO
// if (signerInfs.isEmpty())
// {
// /* RFC 3852 5.2
// * "In the degenerate case where there are no signers, the
// * EncapsulatedContentInfo value being "signed" is irrelevant. In this
// * case, the content type within the EncapsulatedContentInfo value being
// * "signed" MUST be id-data (as defined in section 4), and the content
// * field of the EncapsulatedContentInfo value MUST be omitted."
// */
// if (encapsulate)
// {
// throw new IllegalArgumentException("no signers, encapsulate must be false");
// }
// if (!DATA.equals(eContentType))
// {
// throw new IllegalArgumentException("no signers, eContentType must be id-data");
// }
// }
//
// if (!DATA.equals(eContentType))
// {
// /* RFC 3852 5.3
// * [The 'signedAttrs']...
// * field is optional, but it MUST be present if the content type of
// * the EncapsulatedContentInfo value being signed is not id-data.
// */
// // TODO signedAttrs must be present for all signers
// }
ASN1EncodableVector digestAlgs = new ASN1EncodableVector();
ASN1EncodableVector signerInfos = new ASN1EncodableVector();
// clear the current preserved digest state
digests.clear();
//
for (Iterator it = _signers.iterator(); it.hasNext(); ) {
SignerInformation signer = (SignerInformation) it.next();
digestAlgs.add(CMSSignedHelper.INSTANCE.fixAlgID(signer.getDigestAlgorithmID()));
// TODO Verify the content type and calculated digest match the precalculated SignerInfo
signerInfos.add(signer.toASN1Structure());
}
//
// add the SignerInfo objects
//
ASN1ObjectIdentifier contentTypeOID = content.getContentType();
ASN1OctetString octs = null;
if (content != null) {
ByteArrayOutputStream bOut = null;
if (encapsulate) {
bOut = new ByteArrayOutputStream();
}
OutputStream cOut = CMSUtils.attachSignersToOutputStream(signerGens, bOut);
// Just in case it's unencapsulated and there are no signers!
cOut = CMSUtils.getSafeOutputStream(cOut);
try {
content.write(cOut);
cOut.close();
} catch (IOException e) {
throw new CMSException("data processing exception: " + e.getMessage(), e);
}
if (encapsulate) {
octs = new BEROctetString(bOut.toByteArray());
}
}
for (Iterator it = signerGens.iterator(); it.hasNext(); ) {
SignerInfoGenerator sGen = (SignerInfoGenerator) it.next();
SignerInfo inf = sGen.generate(contentTypeOID);
digestAlgs.add(inf.getDigestAlgorithm());
signerInfos.add(inf);
byte[] calcDigest = sGen.getCalculatedDigest();
if (calcDigest != null) {
digests.put(inf.getDigestAlgorithm().getAlgorithm().getId(), calcDigest);
}
}
ASN1Set certificates = null;
if (certs.size() != 0) {
certificates = CMSUtils.createBerSetFromList(certs);
}
ASN1Set certrevlist = null;
if (crls.size() != 0) {
certrevlist = CMSUtils.createBerSetFromList(crls);
}
ContentInfo encInfo = new ContentInfo(contentTypeOID, octs);
SignedData sd = new SignedData(new DERSet(digestAlgs), encInfo, certificates, certrevlist, new DERSet(signerInfos));
ContentInfo contentInfo = new ContentInfo(CMSObjectIdentifiers.signedData, sd);
return new CMSSignedData(content, contentInfo);
}
use of org.openecard.bouncycastle.asn1.ASN1Set in project robovm by robovm.
the class CMSSignedData method replaceCertificatesAndCRLs.
/**
* Replace the certificate and CRL information associated with this
* CMSSignedData object with the new one passed in.
*
* @param signedData the signed data object to be used as a base.
* @param certsAndCrls the new certificates and CRLs to be used.
* @return a new signed data object.
* @exception CMSException if there is an error processing the CertStore
* @deprecated use method taking Store arguments.
*/
public static CMSSignedData replaceCertificatesAndCRLs(CMSSignedData signedData, CertStore certsAndCrls) throws CMSException {
//
// copy
//
CMSSignedData cms = new CMSSignedData(signedData);
//
// replace the certs and crls in the SignedData object
//
ASN1Set certs = null;
ASN1Set crls = null;
try {
ASN1Set set = CMSUtils.createBerSetFromList(CMSUtils.getCertificatesFromStore(certsAndCrls));
if (set.size() != 0) {
certs = set;
}
} catch (CertStoreException e) {
throw new CMSException("error getting certs from certStore", e);
}
try {
ASN1Set set = CMSUtils.createBerSetFromList(CMSUtils.getCRLsFromStore(certsAndCrls));
if (set.size() != 0) {
crls = set;
}
} catch (CertStoreException e) {
throw new CMSException("error getting crls from certStore", e);
}
//
// replace the CMS structure.
//
cms.signedData = new SignedData(signedData.signedData.getDigestAlgorithms(), signedData.signedData.getEncapContentInfo(), certs, crls, signedData.signedData.getSignerInfos());
//
// replace the contentInfo with the new one
//
cms.contentInfo = new ContentInfo(cms.contentInfo.getContentType(), cms.signedData);
return cms;
}
use of org.openecard.bouncycastle.asn1.ASN1Set in project robovm by robovm.
the class CMSSignedData method replaceSigners.
// BEGIN android-removed
// /**
// * Verify all the SignerInformation objects and their associated counter signatures attached
// * to this CMS SignedData object.
// *
// * @param verifierProvider a provider of SignerInformationVerifier objects.
// * @return true if all verify, false otherwise.
// * @throws CMSException if an exception occurs during the verification process.
// */
// public boolean verifySignatures(SignerInformationVerifierProvider verifierProvider)
// throws CMSException
// {
// return verifySignatures(verifierProvider, false);
// }
//
// /**
// * Verify all the SignerInformation objects and optionally their associated counter signatures attached
// * to this CMS SignedData object.
// *
// * @param verifierProvider a provider of SignerInformationVerifier objects.
// * @param ignoreCounterSignatures if true don't check counter signatures. If false check counter signatures as well.
// * @return true if all verify, false otherwise.
// * @throws CMSException if an exception occurs during the verification process.
// */
// public boolean verifySignatures(SignerInformationVerifierProvider verifierProvider, boolean ignoreCounterSignatures)
// throws CMSException
// {
// Collection signers = this.getSignerInfos().getSigners();
//
// for (Iterator it = signers.iterator(); it.hasNext();)
// {
// SignerInformation signer = (SignerInformation)it.next();
//
// try
// {
// SignerInformationVerifier verifier = verifierProvider.get(signer.getSID());
//
// if (!signer.verify(verifier))
// {
// return false;
// }
//
// if (!ignoreCounterSignatures)
// {
// Collection counterSigners = signer.getCounterSignatures().getSigners();
//
// for (Iterator cIt = counterSigners.iterator(); cIt.hasNext();)
// {
// SignerInformation counterSigner = (SignerInformation)cIt.next();
// SignerInformationVerifier counterVerifier = verifierProvider.get(signer.getSID());
//
// if (!counterSigner.verify(counterVerifier))
// {
// return false;
// }
// }
// }
// }
// catch (OperatorCreationException e)
// {
// throw new CMSException("failure in verifier provider: " + e.getMessage(), e);
// }
// }
//
// return true;
// }
// END android-removed
/**
* Replace the SignerInformation store associated with this
* CMSSignedData object with the new one passed in. You would
* probably only want to do this if you wanted to change the unsigned
* attributes associated with a signer, or perhaps delete one.
*
* @param signedData the signed data object to be used as a base.
* @param signerInformationStore the new signer information store to use.
* @return a new signed data object.
*/
public static CMSSignedData replaceSigners(CMSSignedData signedData, SignerInformationStore signerInformationStore) {
//
// copy
//
CMSSignedData cms = new CMSSignedData(signedData);
//
// replace the store
//
cms.signerInfoStore = signerInformationStore;
//
// replace the signers in the SignedData object
//
ASN1EncodableVector digestAlgs = new ASN1EncodableVector();
ASN1EncodableVector vec = new ASN1EncodableVector();
Iterator it = signerInformationStore.getSigners().iterator();
while (it.hasNext()) {
SignerInformation signer = (SignerInformation) it.next();
digestAlgs.add(CMSSignedHelper.INSTANCE.fixAlgID(signer.getDigestAlgorithmID()));
vec.add(signer.toASN1Structure());
}
ASN1Set digests = new DERSet(digestAlgs);
ASN1Set signers = new DERSet(vec);
ASN1Sequence sD = (ASN1Sequence) signedData.signedData.toASN1Primitive();
vec = new ASN1EncodableVector();
//
// signers are the last item in the sequence.
//
// version
vec.add(sD.getObjectAt(0));
vec.add(digests);
for (int i = 2; i != sD.size() - 1; i++) {
vec.add(sD.getObjectAt(i));
}
vec.add(signers);
cms.signedData = SignedData.getInstance(new BERSequence(vec));
//
// replace the contentInfo with the new one
//
cms.contentInfo = new ContentInfo(cms.contentInfo.getContentType(), cms.signedData);
return cms;
}
Aggregations