use of org.gudy.bouncycastle.asn1.DERObjectIdentifier in project XobotOS by xamarin.
the class X509V2AttributeCertificate method getExtensionOIDs.
private Set getExtensionOIDs(boolean critical) {
X509Extensions extensions = cert.getAcinfo().getExtensions();
if (extensions != null) {
Set set = new HashSet();
Enumeration e = extensions.oids();
while (e.hasMoreElements()) {
DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement();
X509Extension ext = extensions.getExtension(oid);
if (ext.isCritical() == critical) {
set.add(oid.getId());
}
}
return set;
}
return null;
}
use of org.gudy.bouncycastle.asn1.DERObjectIdentifier in project XobotOS by xamarin.
the class PublicKeyFactory method createKey.
/**
* Create a public key from the passed in SubjectPublicKeyInfo
*
* @param keyInfo the SubjectPublicKeyInfo containing the key data
* @return the appropriate key parameter
* @throws IOException on an error decoding the key
*/
public static AsymmetricKeyParameter createKey(SubjectPublicKeyInfo keyInfo) throws IOException {
AlgorithmIdentifier algId = keyInfo.getAlgorithmId();
if (algId.getObjectId().equals(PKCSObjectIdentifiers.rsaEncryption) || algId.getObjectId().equals(X509ObjectIdentifiers.id_ea_rsa)) {
RSAPublicKeyStructure pubKey = new RSAPublicKeyStructure((ASN1Sequence) keyInfo.getPublicKey());
return new RSAKeyParameters(false, pubKey.getModulus(), pubKey.getPublicExponent());
} else if (algId.getObjectId().equals(X9ObjectIdentifiers.dhpublicnumber)) {
DHPublicKey dhPublicKey = DHPublicKey.getInstance(keyInfo.getPublicKey());
BigInteger y = dhPublicKey.getY().getValue();
DHDomainParameters dhParams = DHDomainParameters.getInstance(keyInfo.getAlgorithmId().getParameters());
BigInteger p = dhParams.getP().getValue();
BigInteger g = dhParams.getG().getValue();
BigInteger q = dhParams.getQ().getValue();
BigInteger j = null;
if (dhParams.getJ() != null) {
j = dhParams.getJ().getValue();
}
DHValidationParameters validation = null;
DHValidationParms dhValidationParms = dhParams.getValidationParms();
if (dhValidationParms != null) {
byte[] seed = dhValidationParms.getSeed().getBytes();
BigInteger pgenCounter = dhValidationParms.getPgenCounter().getValue();
// TODO Check pgenCounter size?
validation = new DHValidationParameters(seed, pgenCounter.intValue());
}
return new DHPublicKeyParameters(y, new DHParameters(p, g, q, j, validation));
} else if (algId.getObjectId().equals(PKCSObjectIdentifiers.dhKeyAgreement)) {
DHParameter params = new DHParameter((ASN1Sequence) keyInfo.getAlgorithmId().getParameters());
DERInteger derY = (DERInteger) keyInfo.getPublicKey();
BigInteger lVal = params.getL();
int l = lVal == null ? 0 : lVal.intValue();
DHParameters dhParams = new DHParameters(params.getP(), params.getG(), null, l);
return new DHPublicKeyParameters(derY.getValue(), dhParams);
} else // END android-removed
if (algId.getObjectId().equals(X9ObjectIdentifiers.id_dsa) || algId.getObjectId().equals(OIWObjectIdentifiers.dsaWithSHA1)) {
DERInteger derY = (DERInteger) keyInfo.getPublicKey();
DEREncodable de = keyInfo.getAlgorithmId().getParameters();
DSAParameters parameters = null;
if (de != null) {
DSAParameter params = DSAParameter.getInstance(de.getDERObject());
parameters = new DSAParameters(params.getP(), params.getQ(), params.getG());
}
return new DSAPublicKeyParameters(derY.getValue(), parameters);
} else if (algId.getObjectId().equals(X9ObjectIdentifiers.id_ecPublicKey)) {
X962Parameters params = new X962Parameters((DERObject) keyInfo.getAlgorithmId().getParameters());
ECDomainParameters dParams = null;
if (params.isNamedCurve()) {
DERObjectIdentifier oid = (DERObjectIdentifier) params.getParameters();
X9ECParameters ecP = X962NamedCurves.getByOID(oid);
if (ecP == null) {
ecP = SECNamedCurves.getByOID(oid);
if (ecP == null) {
ecP = NISTNamedCurves.getByOID(oid);
// BEGIN android-removed
// if (ecP == null)
// {
// ecP = TeleTrusTNamedCurves.getByOID(oid);
// }
// END android-removed
}
}
dParams = new ECDomainParameters(ecP.getCurve(), ecP.getG(), ecP.getN(), ecP.getH(), ecP.getSeed());
} else {
X9ECParameters ecP = new X9ECParameters((ASN1Sequence) params.getParameters());
dParams = new ECDomainParameters(ecP.getCurve(), ecP.getG(), ecP.getN(), ecP.getH(), ecP.getSeed());
}
DERBitString bits = keyInfo.getPublicKeyData();
byte[] data = bits.getBytes();
ASN1OctetString key = new DEROctetString(data);
X9ECPoint derQ = new X9ECPoint(dParams.getCurve(), key);
return new ECPublicKeyParameters(derQ.getPoint(), dParams);
} else {
throw new RuntimeException("algorithm identifier in key not recognised");
}
}
use of org.gudy.bouncycastle.asn1.DERObjectIdentifier in project nhin-d by DirectProject.
the class SMIMECryptographerImpl method createSignatureEntity.
protected MimeMultipart createSignatureEntity(byte[] entity, Collection<X509Certificate> signingCertificates) {
MimeMultipart retVal = null;
try {
final MimeBodyPart signedContent = new MimeBodyPart(new ByteArrayInputStream(entity));
final ASN1EncodableVector signedAttrs = new ASN1EncodableVector();
final SMIMECapabilityVector caps = new SMIMECapabilityVector();
caps.addCapability(SMIMECapability.dES_EDE3_CBC);
caps.addCapability(SMIMECapability.rC2_CBC, 128);
caps.addCapability(SMIMECapability.dES_CBC);
caps.addCapability(new DERObjectIdentifier("1.2.840.113549.1.7.1"));
caps.addCapability(x509CertificateObjectsIdent);
signedAttrs.add(new SMIMECapabilitiesAttribute(caps));
final List<X509Certificate> certList = new ArrayList<X509Certificate>();
final DirectSignedDataGenerator generator = sigFactory.createInstance();
for (X509Certificate signer : signingCertificates) {
if (signer instanceof X509CertificateEx) {
generator.addSigner(((X509CertificateEx) signer).getPrivateKey(), signer, this.m_digestAlgorithm.getOID(), createAttributeTable(signedAttrs), null);
certList.add(signer);
}
}
final CertStore certsAndcrls = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), CryptoExtensions.getJCEProviderNameForTypeAndAlgorithm("CertStore", "Collection"));
generator.addCertificatesAndCRLs(certsAndcrls);
final CMSProcessableBodyPart content = new CMSProcessableBodyPart(signedContent);
final CMSSignedData signedData = generator.generate(content);
final String header = "signed; protocol=\"application/pkcs7-signature\"; micalg=" + CryptoAlgorithmsHelper.toDigestAlgorithmMicalg(this.m_digestAlgorithm);
//String encodedSig = Base64.encodeBase64String(signedData.getEncoded());
final String encodedSig = StringUtils.newStringUtf8(Base64.encodeBase64(signedData.getEncoded(), true));
retVal = new MimeMultipart(header.toString());
final MimeBodyPart sig = new MimeBodyPart(new InternetHeaders(), encodedSig.getBytes("ASCII"));
sig.addHeader("Content-Type", "application/pkcs7-signature; name=smime.p7s; smime-type=signed-data");
sig.addHeader("Content-Disposition", "attachment; filename=\"smime.p7s\"");
sig.addHeader("Content-Description", "S/MIME Cryptographic Signature");
sig.addHeader("Content-Transfer-Encoding", "base64");
retVal.addBodyPart(signedContent);
retVal.addBodyPart(sig);
} catch (MessagingException e) {
throw new MimeException(MimeError.InvalidMimeEntity, e);
} catch (IOException e) {
throw new SignatureException(SignatureError.InvalidMultipartSigned, e);
} catch (Exception e) {
throw new NHINDException(MimeError.Unexpected, e);
}
return retVal;
}
use of org.gudy.bouncycastle.asn1.DERObjectIdentifier in project nhin-d by DirectProject.
the class SplitProviderDirectSignedDataGenerator method generate.
/**
* {@inheritDoc}
*/
@Override
public CMSSignedData generate(String signedContentType, CMSProcessable content, boolean encapsulate, String sigProvider, boolean addDefaultAttributes) throws NoSuchAlgorithmException, NoSuchProviderException, CMSException {
final ASN1EncodableVector digestAlgs = new ASN1EncodableVector();
final ASN1EncodableVector signerInfos = new ASN1EncodableVector();
// clear the current preserved digest state
_digests.clear();
//
// add the SignerInfo objects
//
DERObjectIdentifier contentTypeOID;
boolean isCounterSignature;
if (signedContentType != null) {
contentTypeOID = new DERObjectIdentifier(signedContentType);
isCounterSignature = false;
} else {
contentTypeOID = CMSObjectIdentifiers.data;
isCounterSignature = true;
}
for (DirectTargetedSignerInf signer : privateSigners) {
AlgorithmIdentifier digAlgId;
try {
digAlgId = new AlgorithmIdentifier(new DERObjectIdentifier(signer.digestOID), new DERNull());
digestAlgs.add(digAlgId);
try {
signerInfos.add(signer.toSignerInfo(contentTypeOID, content, rand, sigProvider, digestProvider, addDefaultAttributes, isCounterSignature));
} catch (ClassCastException e) {
// try again with the digest provider... the key may need to use a different provider than the sig provider
signerInfos.add(signer.toSignerInfo(contentTypeOID, content, rand, digestProvider, digestProvider, addDefaultAttributes, isCounterSignature));
}
} catch (IOException e) {
throw new CMSException("encoding error.", e);
} catch (InvalidKeyException e) {
throw new CMSException("key inappropriate for signature.", e);
} catch (SignatureException e) {
throw new CMSException("error creating signature.", e);
} catch (CertificateEncodingException e) {
throw new CMSException("error creating sid.", e);
}
}
ASN1Set certificates = null;
if (_certs.size() != 0) {
certificates = createBerSetFromList(_certs);
}
ASN1Set certrevlist = null;
if (_crls.size() != 0) {
certrevlist = createBerSetFromList(_crls);
}
ContentInfo encInfo;
if (encapsulate) {
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
try {
content.write(bOut);
} catch (IOException e) {
throw new CMSException("encapsulation error.", e);
}
ASN1OctetString octs = new BERConstructedOctetString(bOut.toByteArray());
encInfo = new ContentInfo(contentTypeOID, octs);
} else {
encInfo = new ContentInfo(contentTypeOID, null);
}
SignedData sd = new SignedData(new DERSet(digestAlgs), encInfo, certificates, certrevlist, new DERSet(signerInfos));
ContentInfo contentInfo = new ContentInfo(PKCSObjectIdentifiers.signedData, sd);
return new CMSSignedData(content, contentInfo);
}
use of org.gudy.bouncycastle.asn1.DERObjectIdentifier in project android_frameworks_base by AOSPA.
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();
}
Aggregations