use of com.android.org.bouncycastle.asn1.ASN1InputStream in project robovm by robovm.
the class AuthorityKeyIdentifierStructure method fromCertificate.
private static ASN1Sequence fromCertificate(X509Certificate certificate) throws CertificateParsingException {
try {
if (certificate.getVersion() != 3) {
GeneralName genName = new GeneralName(PrincipalUtil.getIssuerX509Principal(certificate));
SubjectPublicKeyInfo info = new SubjectPublicKeyInfo((ASN1Sequence) new ASN1InputStream(certificate.getPublicKey().getEncoded()).readObject());
return (ASN1Sequence) new AuthorityKeyIdentifier(info, new GeneralNames(genName), certificate.getSerialNumber()).toASN1Object();
} else {
GeneralName genName = new GeneralName(PrincipalUtil.getIssuerX509Principal(certificate));
byte[] ext = certificate.getExtensionValue(X509Extensions.SubjectKeyIdentifier.getId());
if (ext != null) {
ASN1OctetString str = (ASN1OctetString) X509ExtensionUtil.fromExtensionValue(ext);
return (ASN1Sequence) new AuthorityKeyIdentifier(str.getOctets(), new GeneralNames(genName), certificate.getSerialNumber()).toASN1Object();
} else {
SubjectPublicKeyInfo info = new SubjectPublicKeyInfo((ASN1Sequence) new ASN1InputStream(certificate.getPublicKey().getEncoded()).readObject());
return (ASN1Sequence) new AuthorityKeyIdentifier(info, new GeneralNames(genName), certificate.getSerialNumber()).toASN1Object();
}
}
} catch (Exception e) {
throw new CertificateParsingException("Exception extracting certificate details: " + e.toString());
}
}
use of com.android.org.bouncycastle.asn1.ASN1InputStream in project platform_frameworks_base by android.
the class ESTHandler method execute.
public void execute(boolean reenroll) throws IOException, GeneralSecurityException {
URL caURL = new URL(mURL.getProtocol(), mURL.getHost(), mURL.getPort(), mURL.getFile() + CACERT_PATH);
HTTPResponse response;
try (HTTPHandler httpHandler = new HTTPHandler(StandardCharsets.ISO_8859_1, mSocketFactory, mUser, mPassword)) {
response = httpHandler.doGetHTTP(caURL);
if (!"application/pkcs7-mime".equals(response.getHeaders().get(HTTPMessage.ContentTypeHeader))) {
throw new IOException("Unexpected Content-Type: " + response.getHeaders().get(HTTPMessage.ContentTypeHeader));
}
ByteBuffer octetBuffer = response.getBinaryPayload();
Collection<Asn1Object> pkcs7Content1 = Asn1Decoder.decode(octetBuffer);
for (Asn1Object asn1Object : pkcs7Content1) {
Log.d(TAG, "---");
Log.d(TAG, asn1Object.toString());
}
Log.d(TAG, CACERT_PATH);
mCACerts.addAll(unpackPkcs7(octetBuffer));
for (X509Certificate certificate : mCACerts) {
Log.d(TAG, "CA-Cert: " + certificate.getSubjectX500Principal());
}
/*
byte[] octets = new byte[octetBuffer.remaining()];
octetBuffer.duplicate().get(octets);
for (byte b : octets) {
System.out.printf("%02x ", b & 0xff);
}
Log.d(TAG, );
*/
/* + BC
try {
byte[] octets = new byte[octetBuffer.remaining()];
octetBuffer.duplicate().get(octets);
ASN1InputStream asnin = new ASN1InputStream(octets);
for (int n = 0; n < 100; n++) {
ASN1Primitive object = asnin.readObject();
if (object == null) {
break;
}
parseObject(object, 0);
}
}
catch (Throwable t) {
t.printStackTrace();
}
Collection<Asn1Object> pkcs7Content = Asn1Decoder.decode(octetBuffer);
for (Asn1Object asn1Object : pkcs7Content) {
Log.d(TAG, asn1Object);
}
if (pkcs7Content.size() != 1) {
throw new IOException("Unexpected pkcs 7 container: " + pkcs7Content.size());
}
Asn1Constructed pkcs7Root = (Asn1Constructed) pkcs7Content.iterator().next();
Iterator<Asn1ID> certPath = Arrays.asList(Pkcs7CertPath).iterator();
Asn1Object certObject = pkcs7Root.findObject(certPath);
if (certObject == null || certPath.hasNext()) {
throw new IOException("Failed to find cert; returned object " + certObject +
", path " + (certPath.hasNext() ? "short" : "exhausted"));
}
ByteBuffer certOctets = certObject.getPayload();
if (certOctets == null) {
throw new IOException("No cert payload in: " + certObject);
}
byte[] certBytes = new byte[certOctets.remaining()];
certOctets.get(certBytes);
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
Certificate cert = certFactory.generateCertificate(new ByteArrayInputStream(certBytes));
Log.d(TAG, "EST Cert: " + cert);
*/
URL csrURL = new URL(mURL.getProtocol(), mURL.getHost(), mURL.getPort(), mURL.getFile() + CSR_PATH);
response = httpHandler.doGetHTTP(csrURL);
octetBuffer = response.getBinaryPayload();
byte[] csrData = buildCSR(octetBuffer, mOMADMAdapter, httpHandler);
/**/
Collection<Asn1Object> o = Asn1Decoder.decode(ByteBuffer.wrap(csrData));
Log.d(TAG, "CSR:");
Log.d(TAG, o.iterator().next().toString());
Log.d(TAG, "End CSR.");
/**/
URL enrollURL = new URL(mURL.getProtocol(), mURL.getHost(), mURL.getPort(), mURL.getFile() + (reenroll ? SIMPLE_REENROLL_PATH : SIMPLE_ENROLL_PATH));
String data = Base64.encodeToString(csrData, Base64.DEFAULT);
octetBuffer = httpHandler.exchangeBinary(enrollURL, data, "application/pkcs10");
Collection<Asn1Object> pkcs7Content2 = Asn1Decoder.decode(octetBuffer);
for (Asn1Object asn1Object : pkcs7Content2) {
Log.d(TAG, "---");
Log.d(TAG, asn1Object.toString());
}
mClientCerts.addAll(unpackPkcs7(octetBuffer));
for (X509Certificate cert : mClientCerts) {
Log.d(TAG, cert.toString());
}
}
}
use of com.android.org.bouncycastle.asn1.ASN1InputStream in project platform_frameworks_base by android.
the class AndroidKeyStoreKeyPairGeneratorSpi method generateSelfSignedCertificateWithFakeSignature.
@SuppressWarnings("deprecation")
private X509Certificate generateSelfSignedCertificateWithFakeSignature(PublicKey publicKey) throws IOException, CertificateParsingException {
V3TBSCertificateGenerator tbsGenerator = new V3TBSCertificateGenerator();
ASN1ObjectIdentifier sigAlgOid;
AlgorithmIdentifier sigAlgId;
byte[] signature;
switch(mKeymasterAlgorithm) {
case KeymasterDefs.KM_ALGORITHM_EC:
sigAlgOid = X9ObjectIdentifiers.ecdsa_with_SHA256;
sigAlgId = new AlgorithmIdentifier(sigAlgOid);
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(new DERInteger(0));
v.add(new DERInteger(0));
signature = new DERSequence().getEncoded();
break;
case KeymasterDefs.KM_ALGORITHM_RSA:
sigAlgOid = PKCSObjectIdentifiers.sha256WithRSAEncryption;
sigAlgId = new AlgorithmIdentifier(sigAlgOid, DERNull.INSTANCE);
signature = new byte[1];
break;
default:
throw new ProviderException("Unsupported key algorithm: " + mKeymasterAlgorithm);
}
try (ASN1InputStream publicKeyInfoIn = new ASN1InputStream(publicKey.getEncoded())) {
tbsGenerator.setSubjectPublicKeyInfo(SubjectPublicKeyInfo.getInstance(publicKeyInfoIn.readObject()));
}
tbsGenerator.setSerialNumber(new ASN1Integer(mSpec.getCertificateSerialNumber()));
X509Principal subject = new X509Principal(mSpec.getCertificateSubject().getEncoded());
tbsGenerator.setSubject(subject);
tbsGenerator.setIssuer(subject);
tbsGenerator.setStartDate(new Time(mSpec.getCertificateNotBefore()));
tbsGenerator.setEndDate(new Time(mSpec.getCertificateNotAfter()));
tbsGenerator.setSignature(sigAlgId);
TBSCertificate tbsCertificate = tbsGenerator.generateTBSCertificate();
ASN1EncodableVector result = new ASN1EncodableVector();
result.add(tbsCertificate);
result.add(sigAlgId);
result.add(new DERBitString(signature));
return new X509CertificateObject(Certificate.getInstance(new DERSequence(result)));
}
use of com.android.org.bouncycastle.asn1.ASN1InputStream in project XobotOS by xamarin.
the class JDKPKCS12KeyStore method engineLoad.
public void engineLoad(InputStream stream, char[] password) throws IOException {
if (// just initialising
stream == null) {
return;
}
if (password == null) {
throw new NullPointerException("No password supplied for PKCS#12 KeyStore.");
}
BufferedInputStream bufIn = new BufferedInputStream(stream);
bufIn.mark(10);
int head = bufIn.read();
if (head != 0x30) {
throw new IOException("stream does not represent a PKCS12 key store");
}
bufIn.reset();
ASN1InputStream bIn = new ASN1InputStream(bufIn);
ASN1Sequence obj = (ASN1Sequence) bIn.readObject();
Pfx bag = new Pfx(obj);
ContentInfo info = bag.getAuthSafe();
Vector chain = new Vector();
boolean unmarkedKey = false;
boolean wrongPKCS12Zero = false;
if (// check the mac code
bag.getMacData() != null) {
MacData mData = bag.getMacData();
DigestInfo dInfo = mData.getMac();
AlgorithmIdentifier algId = dInfo.getAlgorithmId();
byte[] salt = mData.getSalt();
int itCount = mData.getIterationCount().intValue();
byte[] data = ((ASN1OctetString) info.getContent()).getOctets();
try {
byte[] res = calculatePbeMac(algId.getObjectId(), salt, itCount, password, false, data);
byte[] dig = dInfo.getDigest();
if (!Arrays.constantTimeAreEqual(res, dig)) {
if (password.length > 0) {
throw new IOException("PKCS12 key store mac invalid - wrong password or corrupted file.");
}
// Try with incorrect zero length password
res = calculatePbeMac(algId.getObjectId(), salt, itCount, password, true, data);
if (!Arrays.constantTimeAreEqual(res, dig)) {
throw new IOException("PKCS12 key store mac invalid - wrong password or corrupted file.");
}
wrongPKCS12Zero = true;
}
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw new IOException("error constructing MAC: " + e.toString());
}
}
keys = new IgnoresCaseHashtable();
localIds = new Hashtable();
if (info.getContentType().equals(data)) {
bIn = new ASN1InputStream(((ASN1OctetString) info.getContent()).getOctets());
AuthenticatedSafe authSafe = new AuthenticatedSafe((ASN1Sequence) bIn.readObject());
ContentInfo[] c = authSafe.getContentInfo();
for (int i = 0; i != c.length; i++) {
if (c[i].getContentType().equals(data)) {
ASN1InputStream dIn = new ASN1InputStream(((ASN1OctetString) c[i].getContent()).getOctets());
ASN1Sequence seq = (ASN1Sequence) dIn.readObject();
for (int j = 0; j != seq.size(); j++) {
SafeBag b = new SafeBag((ASN1Sequence) seq.getObjectAt(j));
if (b.getBagId().equals(pkcs8ShroudedKeyBag)) {
org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo eIn = new org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo((ASN1Sequence) b.getBagValue());
PrivateKey privKey = unwrapKey(eIn.getEncryptionAlgorithm(), eIn.getEncryptedData(), password, wrongPKCS12Zero);
//
// set the attributes on the key
//
PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) privKey;
String alias = null;
ASN1OctetString localId = null;
if (b.getBagAttributes() != null) {
Enumeration e = b.getBagAttributes().getObjects();
while (e.hasMoreElements()) {
ASN1Sequence sq = (ASN1Sequence) e.nextElement();
DERObjectIdentifier aOid = (DERObjectIdentifier) sq.getObjectAt(0);
ASN1Set attrSet = (ASN1Set) sq.getObjectAt(1);
DERObject attr = null;
if (attrSet.size() > 0) {
attr = (DERObject) attrSet.getObjectAt(0);
DEREncodable existing = bagAttr.getBagAttribute(aOid);
if (existing != null) {
// OK, but the value has to be the same
if (!existing.getDERObject().equals(attr)) {
throw new IOException("attempt to add existing attribute with different value");
}
} else {
bagAttr.setBagAttribute(aOid, attr);
}
}
if (aOid.equals(pkcs_9_at_friendlyName)) {
alias = ((DERBMPString) attr).getString();
keys.put(alias, privKey);
} else if (aOid.equals(pkcs_9_at_localKeyId)) {
localId = (ASN1OctetString) attr;
}
}
}
if (localId != null) {
String name = new String(Hex.encode(localId.getOctets()));
if (alias == null) {
keys.put(name, privKey);
} else {
localIds.put(alias, name);
}
} else {
unmarkedKey = true;
keys.put("unmarked", privKey);
}
} else if (b.getBagId().equals(certBag)) {
chain.addElement(b);
} else {
System.out.println("extra in data " + b.getBagId());
System.out.println(ASN1Dump.dumpAsString(b));
}
}
} else if (c[i].getContentType().equals(encryptedData)) {
EncryptedData d = new EncryptedData((ASN1Sequence) c[i].getContent());
byte[] octets = cryptData(false, d.getEncryptionAlgorithm(), password, wrongPKCS12Zero, d.getContent().getOctets());
ASN1Sequence seq = (ASN1Sequence) ASN1Object.fromByteArray(octets);
for (int j = 0; j != seq.size(); j++) {
SafeBag b = new SafeBag((ASN1Sequence) seq.getObjectAt(j));
if (b.getBagId().equals(certBag)) {
chain.addElement(b);
} else if (b.getBagId().equals(pkcs8ShroudedKeyBag)) {
org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo eIn = new org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo((ASN1Sequence) b.getBagValue());
PrivateKey privKey = unwrapKey(eIn.getEncryptionAlgorithm(), eIn.getEncryptedData(), password, wrongPKCS12Zero);
//
// set the attributes on the key
//
PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) privKey;
String alias = null;
ASN1OctetString localId = null;
Enumeration e = b.getBagAttributes().getObjects();
while (e.hasMoreElements()) {
ASN1Sequence sq = (ASN1Sequence) e.nextElement();
DERObjectIdentifier aOid = (DERObjectIdentifier) sq.getObjectAt(0);
ASN1Set attrSet = (ASN1Set) sq.getObjectAt(1);
DERObject attr = null;
if (attrSet.size() > 0) {
attr = (DERObject) attrSet.getObjectAt(0);
DEREncodable existing = bagAttr.getBagAttribute(aOid);
if (existing != null) {
// OK, but the value has to be the same
if (!existing.getDERObject().equals(attr)) {
throw new IOException("attempt to add existing attribute with different value");
}
} else {
bagAttr.setBagAttribute(aOid, attr);
}
}
if (aOid.equals(pkcs_9_at_friendlyName)) {
alias = ((DERBMPString) attr).getString();
keys.put(alias, privKey);
} else if (aOid.equals(pkcs_9_at_localKeyId)) {
localId = (ASN1OctetString) attr;
}
}
String name = new String(Hex.encode(localId.getOctets()));
if (alias == null) {
keys.put(name, privKey);
} else {
localIds.put(alias, name);
}
} else if (b.getBagId().equals(keyBag)) {
org.bouncycastle.asn1.pkcs.PrivateKeyInfo pIn = new org.bouncycastle.asn1.pkcs.PrivateKeyInfo((ASN1Sequence) b.getBagValue());
PrivateKey privKey = JDKKeyFactory.createPrivateKeyFromPrivateKeyInfo(pIn);
//
// set the attributes on the key
//
PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) privKey;
String alias = null;
ASN1OctetString localId = null;
Enumeration e = b.getBagAttributes().getObjects();
while (e.hasMoreElements()) {
ASN1Sequence sq = (ASN1Sequence) e.nextElement();
DERObjectIdentifier aOid = (DERObjectIdentifier) sq.getObjectAt(0);
ASN1Set attrSet = (ASN1Set) sq.getObjectAt(1);
DERObject attr = null;
if (attrSet.size() > 0) {
attr = (DERObject) attrSet.getObjectAt(0);
DEREncodable existing = bagAttr.getBagAttribute(aOid);
if (existing != null) {
// OK, but the value has to be the same
if (!existing.getDERObject().equals(attr)) {
throw new IOException("attempt to add existing attribute with different value");
}
} else {
bagAttr.setBagAttribute(aOid, attr);
}
}
if (aOid.equals(pkcs_9_at_friendlyName)) {
alias = ((DERBMPString) attr).getString();
keys.put(alias, privKey);
} else if (aOid.equals(pkcs_9_at_localKeyId)) {
localId = (ASN1OctetString) attr;
}
}
String name = new String(Hex.encode(localId.getOctets()));
if (alias == null) {
keys.put(name, privKey);
} else {
localIds.put(alias, name);
}
} else {
System.out.println("extra in encryptedData " + b.getBagId());
System.out.println(ASN1Dump.dumpAsString(b));
}
}
} else {
System.out.println("extra " + c[i].getContentType().getId());
System.out.println("extra " + ASN1Dump.dumpAsString(c[i].getContent()));
}
}
}
certs = new IgnoresCaseHashtable();
chainCerts = new Hashtable();
keyCerts = new Hashtable();
for (int i = 0; i != chain.size(); i++) {
SafeBag b = (SafeBag) chain.elementAt(i);
CertBag cb = new CertBag((ASN1Sequence) b.getBagValue());
if (!cb.getCertId().equals(x509Certificate)) {
throw new RuntimeException("Unsupported certificate type: " + cb.getCertId());
}
Certificate cert;
try {
ByteArrayInputStream cIn = new ByteArrayInputStream(((ASN1OctetString) cb.getCertValue()).getOctets());
cert = certFact.generateCertificate(cIn);
} catch (Exception e) {
throw new RuntimeException(e.toString());
}
//
// set the attributes
//
ASN1OctetString localId = null;
String alias = null;
if (b.getBagAttributes() != null) {
Enumeration e = b.getBagAttributes().getObjects();
while (e.hasMoreElements()) {
ASN1Sequence sq = (ASN1Sequence) e.nextElement();
DERObjectIdentifier oid = (DERObjectIdentifier) sq.getObjectAt(0);
DERObject attr = (DERObject) ((ASN1Set) sq.getObjectAt(1)).getObjectAt(0);
PKCS12BagAttributeCarrier bagAttr = null;
if (cert instanceof PKCS12BagAttributeCarrier) {
bagAttr = (PKCS12BagAttributeCarrier) cert;
DEREncodable existing = bagAttr.getBagAttribute(oid);
if (existing != null) {
// OK, but the value has to be the same
if (!existing.getDERObject().equals(attr)) {
throw new IOException("attempt to add existing attribute with different value");
}
} else {
bagAttr.setBagAttribute(oid, attr);
}
}
if (oid.equals(pkcs_9_at_friendlyName)) {
alias = ((DERBMPString) attr).getString();
} else if (oid.equals(pkcs_9_at_localKeyId)) {
localId = (ASN1OctetString) attr;
}
}
}
chainCerts.put(new CertId(cert.getPublicKey()), cert);
if (unmarkedKey) {
if (keyCerts.isEmpty()) {
String name = new String(Hex.encode(createSubjectKeyId(cert.getPublicKey()).getKeyIdentifier()));
keyCerts.put(name, cert);
keys.put(name, keys.remove("unmarked"));
}
} else {
//
if (localId != null) {
String name = new String(Hex.encode(localId.getOctets()));
keyCerts.put(name, cert);
}
if (alias != null) {
certs.put(alias, cert);
}
}
}
}
use of com.android.org.bouncycastle.asn1.ASN1InputStream in project XobotOS by xamarin.
the class JDKX509CertificateFactory method engineGenerateCertificate.
/**
* Generates a certificate object and initializes it with the data
* read from the input stream inStream.
*/
public Certificate engineGenerateCertificate(InputStream in) throws CertificateException {
if (currentStream == null) {
currentStream = in;
sData = null;
sDataObjectCount = 0;
} else if (// reset if input stream has changed
currentStream != in) {
currentStream = in;
sData = null;
sDataObjectCount = 0;
}
try {
if (sData != null) {
if (sDataObjectCount != sData.size()) {
return getCertificate();
} else {
sData = null;
sDataObjectCount = 0;
return null;
}
}
int limit = ProviderUtil.getReadLimit(in);
PushbackInputStream pis = new PushbackInputStream(in);
int tag = pis.read();
if (tag == -1) {
return null;
}
pis.unread(tag);
if (// assume ascii PEM encoded.
tag != 0x30) {
return readPEMCertificate(pis);
} else {
return readDERCertificate(new ASN1InputStream(pis, limit));
}
} catch (Exception e) {
throw new CertificateException(e);
}
}
Aggregations