use of org.bouncycastle.asn1.DERBitString in project android_frameworks_base by crdroidandroid.
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.bouncycastle.asn1.DERBitString in project xipki by xipki.
the class Foo method createRequest.
private static byte[] createRequest(Control control) throws Exception {
GeneralName requestorName = control.withRequestName ? new GeneralName(new X500Name("CN=requestor1")) : null;
AlgorithmIdentifier algId1 = new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1, DERNull.INSTANCE);
CertID certId1 = new CertID(algId1, new DEROctetString(newBytes(20, (byte) 0x11)), new DEROctetString(newBytes(20, (byte) 0x12)), new ASN1Integer(BigInteger.valueOf(0x1234)));
Request request1 = new Request(certId1, null);
AlgorithmIdentifier algId2 = new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1);
CertID certId2 = new CertID(algId2, new DEROctetString(newBytes(20, (byte) 0x21)), new DEROctetString(newBytes(20, (byte) 0x22)), new ASN1Integer(BigInteger.valueOf(0x1235)));
Request request2 = new Request(certId2, new Extensions(new Extension(ObjectIdentifiers.id_ad_timeStamping, false, newBytes(30, (byte) 0x33))));
// CHECKSTYLE:SKIP
ASN1Sequence requestList = new DERSequence(new ASN1Encodable[] { request1, request2 });
Extensions requestExtensions = null;
if (control.withNonce || control.withPrefSigAlgs) {
int size = 0;
if (control.withNonce) {
size++;
}
if (control.withPrefSigAlgs) {
size++;
}
Extension[] arrays = new Extension[size];
int offset = 0;
if (control.withNonce) {
arrays[offset++] = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, control.extensionCritical, newBytes(20, (byte) 0x44));
}
if (control.withPrefSigAlgs) {
AlgorithmIdentifier sigAlg1 = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha256WithRSAEncryption, DERNull.INSTANCE);
AlgorithmIdentifier sigAlg2 = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption, DERNull.INSTANCE);
ASN1Sequence seq = new DERSequence(new ASN1Encodable[] { sigAlg1, sigAlg2 });
arrays[offset++] = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_pref_sig_algs, control.extensionCritical, seq.getEncoded());
}
requestExtensions = new Extensions(arrays);
}
ASN1EncodableVector vec = new ASN1EncodableVector();
if (control.version != 0) {
vec.add(new DERTaggedObject(true, 0, new ASN1Integer(BigInteger.valueOf(control.version))));
}
if (requestorName != null) {
vec.add(new DERTaggedObject(true, 1, requestorName));
}
vec.add(requestList);
if (requestExtensions != null) {
vec.add(new DERTaggedObject(true, 2, requestExtensions));
}
TBSRequest tbsRequest = TBSRequest.getInstance(new DERSequence(vec));
Signature sig = null;
if (control.withSignature) {
sig = new Signature(new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption), new DERBitString(newBytes(256, (byte) 0xFF)));
}
return new OCSPRequest(tbsRequest, sig).getEncoded();
}
use of org.bouncycastle.asn1.DERBitString in project xipki by xipki.
the class XiOCSPReqBuilder method generateRequest.
private OCSPRequest generateRequest(ContentSigner contentSigner, Certificate[] chain) throws OCSPException {
Iterator<RequestObject> it = list.iterator();
ASN1EncodableVector requests = new ASN1EncodableVector();
while (it.hasNext()) {
try {
requests.add(((RequestObject) it.next()).toRequest());
} catch (Exception ex) {
throw new OCSPException("exception creating Request", ex);
}
}
TBSRequest tbsReq = new TBSRequest(requestorName, new DERSequence(requests), requestExtensions);
Signature signature = null;
if (contentSigner != null) {
if (requestorName == null) {
throw new OCSPException("requestorName must be specified if request is signed.");
}
try {
// CHECKSTYLE:SKIP
OutputStream sOut = contentSigner.getOutputStream();
sOut.write(tbsReq.getEncoded(ASN1Encoding.DER));
sOut.close();
} catch (Exception ex) {
throw new OCSPException("exception processing TBSRequest: " + ex, ex);
}
DERBitString bitSig = new DERBitString(contentSigner.getSignature());
AlgorithmIdentifier sigAlgId = contentSigner.getAlgorithmIdentifier();
if (chain != null && chain.length > 0) {
ASN1EncodableVector vec = new ASN1EncodableVector();
for (int i = 0; i != chain.length; i++) {
vec.add(chain[i]);
}
signature = new Signature(sigAlgId, bitSig, new DERSequence(vec));
} else {
signature = new Signature(sigAlgId, bitSig);
}
}
return new OCSPRequest(tbsReq, signature);
}
use of org.bouncycastle.asn1.DERBitString in project candlepin by candlepin.
the class X509CRLStreamWriter method handleHeader.
protected int handleHeader(OutputStream out) throws IOException {
/* The length of an RSA signature is padded out to the length of the modulus
* in bytes. See http://stackoverflow.com/questions/6658728/rsa-signature-size
*
* If the original CRL was signed with a 2048 bit key and someone sends in a
* 4096 bit key, we need to account for the discrepancy.
*/
int newSigBytes = key.getModulus().bitLength() / 8;
/* Now we need a byte array to figure out how long the new signature will
* be when encoded.
*/
byte[] dummySig = new byte[newSigBytes];
Arrays.fill(dummySig, (byte) 0x00);
this.newSigLength = new DERBitString(dummySig).getEncoded().length;
int addedEntriesLength = 0;
for (ASN1Sequence s : newEntries) {
addedEntriesLength += s.getEncoded().length;
}
int topTag = readTag(crlIn, null);
int topTagNo = readTagNumber(crlIn, topTag, null);
int oldTotalLength = readLength(crlIn, null);
// Now we are in the TBSCertList
int tbsTag = readTag(crlIn, null);
int tbsTagNo = readTagNumber(crlIn, tbsTag, null);
int oldTbsLength = readLength(crlIn, null);
/* We may need to adjust the overall length of the tbsCertList
* based on changes in the revokedCertificates sequence, so we
* will cache the tbsCertList data in this temporary byte stream.
*/
ByteArrayOutputStream temp = new ByteArrayOutputStream();
int tagNo;
Date oldThisUpdate;
boolean signatureReplaced = false;
while (true) {
int tag = readTag(crlIn, null);
tagNo = readTagNumber(crlIn, tag, null);
// then not worry with other sequences.
if (tagNo == SEQUENCE && !signatureReplaced) {
readAndReplaceSignatureAlgorithm(temp);
signatureReplaced = true;
} else if (tagNo == GENERALIZED_TIME || tagNo == UTC_TIME) {
oldThisUpdate = readAndReplaceTime(temp, tagNo);
break;
} else {
writeTag(temp, tag, tagNo);
int length = echoLength(temp);
echoValue(temp, length);
}
}
// Now we have to deal with the potential for an optional nextUpdate field
int tag = readTag(crlIn, null);
tagNo = readTagNumber(crlIn, tag, null);
if (tagNo == GENERALIZED_TIME || tagNo == UTC_TIME) {
/* It would be possible to take in a desired nextUpdate in the constructor
* but I'm not sure if the added complexity is worth it.
*/
offsetNextUpdate(temp, tagNo, oldThisUpdate);
echoTag(temp);
} else {
writeTag(temp, tag, tagNo);
}
/* Much like throwing a stone into a pond, as one sequence increases in
* length the change can ripple out to parent sequences as more bytes are
* required to encode the length. For example, if we have a tbsCertList of
* size 250 and a revokedCertificates list of size 100, the revokedCertificates
* list size could increase by 6 with no change in the length bytes its sequence
* requires. However, 250 + 6 extra bytes equals a total length of 256 which
* requires 2 bytes to encode instead of 1, thus changing the total length
* of the CertificateList sequence.
*
* We account for these ripples with the xxxHeaderBytesDelta variables.
*/
int revokedCertsLengthDelta = addedEntriesLength - deletedEntriesLength;
int oldRevokedCertsLength = readLength(crlIn, null);
int newRevokedCertsLength = oldRevokedCertsLength + revokedCertsLengthDelta;
int revokedCertsHeaderBytesDelta = findHeaderBytesDelta(oldRevokedCertsLength, newRevokedCertsLength);
int tbsCertListLengthDelta = revokedCertsLengthDelta + revokedCertsHeaderBytesDelta + extensionsDelta;
int newTbsLength = oldTbsLength + tbsCertListLengthDelta;
int tbsHeaderBytesDelta = findHeaderBytesDelta(oldTbsLength, newTbsLength);
// newSigLength represents a DER encoded signature so it already contains the header bytes delta.
int sigLengthDelta = newSigLength - oldSigLength;
int totalLengthDelta = tbsCertListLengthDelta + tbsHeaderBytesDelta + sigLengthDelta;
int newTotalLength = oldTotalLength + totalLengthDelta;
/* NB: The top level sequence isn't part of the signature so its tag and
* length do not go through the signer.
*/
writeTag(out, topTag, topTagNo);
writeLength(out, newTotalLength);
writeTag(out, tbsTag, tbsTagNo, signer);
writeLength(out, newTbsLength, signer);
byte[] header = temp.toByteArray();
temp.close();
out.write(header);
signer.getOutputStream().write(header, 0, header.length);
writeLength(out, newRevokedCertsLength, signer);
return oldRevokedCertsLength;
}
use of org.bouncycastle.asn1.DERBitString in project keystore-explorer by kaikramer.
the class X509Ext method getEntrustVersionInformationStringValue.
private String getEntrustVersionInformationStringValue(byte[] value) throws IOException {
// @formatter:off
/*
* EntrustVersInfoSyntax ::= OCTET STRING
*
* entrustVersInfo EXTENSION ::= { SYNTAX EntrustVersInfoSyntax,
* IDENTIFIED BY {id-entrust 0} }
*
* EntrustVersInfoSyntax ::= ASN1Sequence { entrustVers GeneralString,
* entrustInfoFlags EntrustInfoFlags }
*
* EntrustInfoFlags ::= BIT STRING { keyUpdateAllowed newExtensions (1),
* pKIXCertificate (2) }
*/
// @formatter:on
StringBuilder sb = new StringBuilder();
ASN1Sequence entrustVersInfo = (ASN1Sequence) ASN1Primitive.fromByteArray(value);
DERGeneralString entrustVers = (DERGeneralString) entrustVersInfo.getObjectAt(0);
DERBitString entrustInfoFlags = (DERBitString) entrustVersInfo.getObjectAt(1);
sb.append(MessageFormat.format(res.getString("EntrustVersion"), entrustVers.getString()));
sb.append(NEWLINE);
sb.append(MessageFormat.format(res.getString("EntrustInformationFlags"), entrustInfoFlags.getString()));
sb.append(NEWLINE);
return sb.toString();
}
Aggregations