use of com.android.org.bouncycastle.asn1.x509.Attribute 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 com.android.org.bouncycastle.asn1.x509.Attribute 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 com.android.org.bouncycastle.asn1.x509.Attribute in project nhin-d by DirectProject.
the class MessageSigInspector method main.
public static void main(String[] args) {
if (args.length == 0) {
//printUsage();
System.exit(-1);
}
String messgefile = null;
for (int i = 0; i < args.length; i++) {
String arg = args[i];
// Options
if (!arg.startsWith("-")) {
System.err.println("Error: Unexpected argument [" + arg + "]\n");
//printUsage();
System.exit(-1);
} else if (arg.equalsIgnoreCase("-msgFile")) {
if (i == args.length - 1 || args[i + 1].startsWith("-")) {
System.err.println("Error: Missing message file");
System.exit(-1);
}
messgefile = args[++i];
} else if (arg.equals("-help")) {
//printUsage();
System.exit(-1);
} else {
System.err.println("Error: Unknown argument " + arg + "\n");
//printUsage();
System.exit(-1);
}
}
if (messgefile == null) {
System.err.println("Error: missing message file\n");
}
InputStream inStream = null;
try {
inStream = FileUtils.openInputStream(new File(messgefile));
MimeMessage message = new MimeMessage(null, inStream);
MimeMultipart mm = (MimeMultipart) message.getContent();
//byte[] messageBytes = EntitySerializer.Default.serializeToBytes(mm.getBodyPart(0).getContent());
//MimeBodyPart signedContent = null;
//signedContent = new MimeBodyPart(new ByteArrayInputStream(messageBytes));
final CMSSignedData signed = new CMSSignedData(new CMSProcessableBodyPart(mm.getBodyPart(0)), mm.getBodyPart(1).getInputStream());
CertStore certs = signed.getCertificatesAndCRLs("Collection", CryptoExtensions.getJCEProviderName());
SignerInformationStore signers = signed.getSignerInfos();
@SuppressWarnings("unchecked") Collection<SignerInformation> c = signers.getSigners();
System.out.println("Found " + c.size() + " signers");
int cnt = 1;
for (SignerInformation signer : c) {
Collection<? extends Certificate> certCollection = certs.getCertificates(signer.getSID());
if (certCollection != null && certCollection.size() > 0) {
X509Certificate cert = (X509Certificate) certCollection.iterator().next();
System.out.println("\r\nInfo for certificate " + cnt++);
System.out.println("\tSubject " + cert.getSubjectDN());
FileUtils.writeByteArrayToFile(new File("SigCert.der"), cert.getEncoded());
byte[] bytes = cert.getExtensionValue("2.5.29.15");
if (bytes != null) {
final DERObject obj = getObject(bytes);
final KeyUsage keyUsage = new KeyUsage((DERBitString) obj);
final byte[] data = keyUsage.getBytes();
final int intValue = (data.length == 1) ? data[0] & 0xff : (data[1] & 0xff) << 8 | (data[0] & 0xff);
System.out.println("\tKey Usage: " + intValue);
} else
System.out.println("\tKey Usage: NONE");
//verify and get the digests
final Attribute digAttr = signer.getSignedAttributes().get(CMSAttributes.messageDigest);
final DERObject hashObj = digAttr.getAttrValues().getObjectAt(0).getDERObject();
final byte[] signedDigest = ((ASN1OctetString) hashObj).getOctets();
final String signedDigestHex = org.apache.commons.codec.binary.Hex.encodeHexString(signedDigest);
System.out.println("\r\nSigned Message Digest: " + signedDigestHex);
try {
signer.verify(cert, "BC");
System.out.println("Signature verified.");
} catch (CMSException e) {
System.out.println("Signature failed to verify.");
}
// should have the computed digest now
final byte[] digest = signer.getContentDigest();
final String digestHex = org.apache.commons.codec.binary.Hex.encodeHexString(digest);
System.out.println("\r\nComputed Message Digest: " + digestHex);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(inStream);
}
}
use of com.android.org.bouncycastle.asn1.x509.Attribute in project robovm by robovm.
the class SignerInformation method doVerify.
private boolean doVerify(SignerInformationVerifier verifier) throws CMSException {
String encName = CMSSignedHelper.INSTANCE.getEncryptionAlgName(this.getEncryptionAlgOID());
ContentVerifier contentVerifier;
try {
contentVerifier = verifier.getContentVerifier(encryptionAlgorithm, info.getDigestAlgorithm());
} catch (OperatorCreationException e) {
throw new CMSException("can't create content verifier: " + e.getMessage(), e);
}
try {
OutputStream sigOut = contentVerifier.getOutputStream();
if (resultDigest == null) {
DigestCalculator calc = verifier.getDigestCalculator(this.getDigestAlgorithmID());
if (content != null) {
OutputStream digOut = calc.getOutputStream();
if (signedAttributeSet == null) {
if (contentVerifier instanceof RawContentVerifier) {
content.write(digOut);
} else {
OutputStream cOut = new TeeOutputStream(digOut, sigOut);
content.write(cOut);
cOut.close();
}
} else {
content.write(digOut);
sigOut.write(this.getEncodedSignedAttributes());
}
digOut.close();
} else if (signedAttributeSet != null) {
sigOut.write(this.getEncodedSignedAttributes());
} else {
// TODO Get rid of this exception and just treat content==null as empty not missing?
throw new CMSException("data not encapsulated in signature - use detached constructor.");
}
resultDigest = calc.getDigest();
} else {
if (signedAttributeSet == null) {
if (content != null) {
content.write(sigOut);
}
} else {
sigOut.write(this.getEncodedSignedAttributes());
}
}
sigOut.close();
} catch (IOException e) {
throw new CMSException("can't process mime object to create signature.", e);
} catch (OperatorCreationException e) {
throw new CMSException("can't create digest calculator: " + e.getMessage(), e);
}
// RFC 3852 11.1 Check the content-type attribute is correct
{
ASN1Primitive validContentType = getSingleValuedSignedAttribute(CMSAttributes.contentType, "content-type");
if (validContentType == null) {
if (!isCounterSignature && signedAttributeSet != null) {
throw new CMSException("The content-type attribute type MUST be present whenever signed attributes are present in signed-data");
}
} else {
if (isCounterSignature) {
throw new CMSException("[For counter signatures,] the signedAttributes field MUST NOT contain a content-type attribute");
}
if (!(validContentType instanceof ASN1ObjectIdentifier)) {
throw new CMSException("content-type attribute value not of ASN.1 type 'OBJECT IDENTIFIER'");
}
ASN1ObjectIdentifier signedContentType = (ASN1ObjectIdentifier) validContentType;
if (!signedContentType.equals(contentType)) {
throw new CMSException("content-type attribute value does not match eContentType");
}
}
}
// RFC 3852 11.2 Check the message-digest attribute is correct
{
ASN1Primitive validMessageDigest = getSingleValuedSignedAttribute(CMSAttributes.messageDigest, "message-digest");
if (validMessageDigest == null) {
if (signedAttributeSet != null) {
throw new CMSException("the message-digest signed attribute type MUST be present when there are any signed attributes present");
}
} else {
if (!(validMessageDigest instanceof ASN1OctetString)) {
throw new CMSException("message-digest attribute value not of ASN.1 type 'OCTET STRING'");
}
ASN1OctetString signedMessageDigest = (ASN1OctetString) validMessageDigest;
if (!Arrays.constantTimeAreEqual(resultDigest, signedMessageDigest.getOctets())) {
throw new CMSSignerDigestMismatchException("message-digest attribute value does not match calculated value");
}
}
}
// RFC 3852 11.4 Validate countersignature attribute(s)
{
AttributeTable signedAttrTable = this.getSignedAttributes();
if (signedAttrTable != null && signedAttrTable.getAll(CMSAttributes.counterSignature).size() > 0) {
throw new CMSException("A countersignature attribute MUST NOT be a signed attribute");
}
AttributeTable unsignedAttrTable = this.getUnsignedAttributes();
if (unsignedAttrTable != null) {
ASN1EncodableVector csAttrs = unsignedAttrTable.getAll(CMSAttributes.counterSignature);
for (int i = 0; i < csAttrs.size(); ++i) {
Attribute csAttr = (Attribute) csAttrs.get(i);
if (csAttr.getAttrValues().size() < 1) {
throw new CMSException("A countersignature attribute MUST contain at least one AttributeValue");
}
// Note: We don't recursively validate the countersignature value
}
}
}
try {
if (signedAttributeSet == null && resultDigest != null) {
if (contentVerifier instanceof RawContentVerifier) {
RawContentVerifier rawVerifier = (RawContentVerifier) contentVerifier;
if (encName.equals("RSA")) {
DigestInfo digInfo = new DigestInfo(new AlgorithmIdentifier(digestAlgorithm.getAlgorithm(), DERNull.INSTANCE), resultDigest);
return rawVerifier.verify(digInfo.getEncoded(ASN1Encoding.DER), this.getSignature());
}
return rawVerifier.verify(resultDigest, this.getSignature());
}
}
return contentVerifier.verify(this.getSignature());
} catch (IOException e) {
throw new CMSException("can't process mime object to create signature.", e);
}
}
use of com.android.org.bouncycastle.asn1.x509.Attribute in project robovm by robovm.
the class X509AttributeCertificateHolder method isSignatureValid.
/**
* Validate the signature on the attribute certificate in this holder.
*
* @param verifierProvider a ContentVerifierProvider that can generate a verifier for the signature.
* @return true if the signature is valid, false otherwise.
* @throws CertException if the signature cannot be processed or is inappropriate.
*/
public boolean isSignatureValid(ContentVerifierProvider verifierProvider) throws CertException {
AttributeCertificateInfo acinfo = attrCert.getAcinfo();
if (!CertUtils.isAlgIdEqual(acinfo.getSignature(), attrCert.getSignatureAlgorithm())) {
throw new CertException("signature invalid - algorithm identifier mismatch");
}
ContentVerifier verifier;
try {
verifier = verifierProvider.get((acinfo.getSignature()));
OutputStream sOut = verifier.getOutputStream();
DEROutputStream dOut = new DEROutputStream(sOut);
dOut.writeObject(acinfo);
sOut.close();
} catch (Exception e) {
throw new CertException("unable to process signature: " + e.getMessage(), e);
}
return verifier.verify(attrCert.getSignatureValue().getBytes());
}
Aggregations