use of org.bouncycastle.asn1.ASN1BMPString in project LinLong-Java by zhenwei1108.
the class ASN1Dump method _dumpAsString.
/**
* dump a DER object as a formatted string with indentation
*
* @param obj the ASN1Primitive to be dumped out.
*/
static void _dumpAsString(String indent, boolean verbose, ASN1Primitive obj, StringBuffer buf) {
String nl = Strings.lineSeparator();
if (obj instanceof ASN1Null) {
buf.append(indent);
buf.append("NULL");
buf.append(nl);
} else if (obj instanceof ASN1Sequence) {
buf.append(indent);
if (obj instanceof BERSequence) {
buf.append("BER Sequence");
} else if (obj instanceof DERSequence) {
buf.append("DER Sequence");
} else {
buf.append("Sequence");
}
buf.append(nl);
ASN1Sequence sequence = (ASN1Sequence) obj;
String elementsIndent = indent + TAB;
for (int i = 0, count = sequence.size(); i < count; ++i) {
_dumpAsString(elementsIndent, verbose, sequence.getObjectAt(i).toASN1Primitive(), buf);
}
} else if (obj instanceof ASN1Set) {
buf.append(indent);
if (obj instanceof BERSet) {
buf.append("BER Set");
} else if (obj instanceof DERSet) {
buf.append("DER Set");
} else {
buf.append("Set");
}
buf.append(nl);
ASN1Set set = (ASN1Set) obj;
String elementsIndent = indent + TAB;
for (int i = 0, count = set.size(); i < count; ++i) {
_dumpAsString(elementsIndent, verbose, set.getObjectAt(i).toASN1Primitive(), buf);
}
} else if (obj instanceof ASN1ApplicationSpecific) {
_dumpAsString(indent, verbose, ((ASN1ApplicationSpecific) obj).getTaggedObject(), buf);
} else if (obj instanceof ASN1TaggedObject) {
buf.append(indent);
if (obj instanceof BERTaggedObject) {
buf.append("BER Tagged ");
} else if (obj instanceof DERTaggedObject) {
buf.append("DER Tagged ");
} else {
buf.append("Tagged ");
}
ASN1TaggedObject o = (ASN1TaggedObject) obj;
buf.append(ASN1Util.getTagText(o));
if (!o.isExplicit()) {
buf.append(" IMPLICIT ");
}
buf.append(nl);
String baseIndent = indent + TAB;
_dumpAsString(baseIndent, verbose, o.getBaseObject().toASN1Primitive(), buf);
} else if (obj instanceof ASN1OctetString) {
ASN1OctetString oct = (ASN1OctetString) obj;
if (obj instanceof BEROctetString) {
buf.append(indent + "BER Constructed Octet String" + "[" + oct.getOctets().length + "] ");
} else {
buf.append(indent + "DER Octet String" + "[" + oct.getOctets().length + "] ");
}
if (verbose) {
buf.append(dumpBinaryDataAsString(indent, oct.getOctets()));
} else {
buf.append(nl);
}
} else if (obj instanceof ASN1ObjectIdentifier) {
buf.append(indent + "ObjectIdentifier(" + ((ASN1ObjectIdentifier) obj).getId() + ")" + nl);
} else if (obj instanceof ASN1RelativeOID) {
buf.append(indent + "RelativeOID(" + ((ASN1RelativeOID) obj).getId() + ")" + nl);
} else if (obj instanceof ASN1Boolean) {
buf.append(indent + "Boolean(" + ((ASN1Boolean) obj).isTrue() + ")" + nl);
} else if (obj instanceof ASN1Integer) {
buf.append(indent + "Integer(" + ((ASN1Integer) obj).getValue() + ")" + nl);
} else if (obj instanceof ASN1BitString) {
ASN1BitString bitString = (ASN1BitString) obj;
byte[] bytes = bitString.getBytes();
int padBits = bitString.getPadBits();
if (bitString instanceof DERBitString) {
buf.append(indent + "DER Bit String" + "[" + bytes.length + ", " + padBits + "] ");
} else if (bitString instanceof DLBitString) {
buf.append(indent + "DL Bit String" + "[" + bytes.length + ", " + padBits + "] ");
} else {
buf.append(indent + "BER Bit String" + "[" + bytes.length + ", " + padBits + "] ");
}
if (verbose) {
buf.append(dumpBinaryDataAsString(indent, bytes));
} else {
buf.append(nl);
}
} else if (obj instanceof ASN1IA5String) {
buf.append(indent + "IA5String(" + ((ASN1IA5String) obj).getString() + ") " + nl);
} else if (obj instanceof ASN1UTF8String) {
buf.append(indent + "UTF8String(" + ((ASN1UTF8String) obj).getString() + ") " + nl);
} else if (obj instanceof ASN1NumericString) {
buf.append(indent + "NumericString(" + ((ASN1NumericString) obj).getString() + ") " + nl);
} else if (obj instanceof ASN1PrintableString) {
buf.append(indent + "PrintableString(" + ((ASN1PrintableString) obj).getString() + ") " + nl);
} else if (obj instanceof ASN1VisibleString) {
buf.append(indent + "VisibleString(" + ((ASN1VisibleString) obj).getString() + ") " + nl);
} else if (obj instanceof ASN1BMPString) {
buf.append(indent + "BMPString(" + ((ASN1BMPString) obj).getString() + ") " + nl);
} else if (obj instanceof ASN1T61String) {
buf.append(indent + "T61String(" + ((ASN1T61String) obj).getString() + ") " + nl);
} else if (obj instanceof ASN1GraphicString) {
buf.append(indent + "GraphicString(" + ((ASN1GraphicString) obj).getString() + ") " + nl);
} else if (obj instanceof ASN1VideotexString) {
buf.append(indent + "VideotexString(" + ((ASN1VideotexString) obj).getString() + ") " + nl);
} else if (obj instanceof ASN1UTCTime) {
buf.append(indent + "UTCTime(" + ((ASN1UTCTime) obj).getTime() + ") " + nl);
} else if (obj instanceof ASN1GeneralizedTime) {
buf.append(indent + "GeneralizedTime(" + ((ASN1GeneralizedTime) obj).getTime() + ") " + nl);
} else if (obj instanceof ASN1Enumerated) {
ASN1Enumerated en = (ASN1Enumerated) obj;
buf.append(indent + "DER Enumerated(" + en.getValue() + ")" + nl);
} else if (obj instanceof ASN1ObjectDescriptor) {
ASN1ObjectDescriptor od = (ASN1ObjectDescriptor) obj;
buf.append(indent + "ObjectDescriptor(" + od.getBaseGraphicString().getString() + ") " + nl);
} else if (obj instanceof ASN1External) {
ASN1External ext = (ASN1External) obj;
buf.append(indent + "External " + nl);
String tab = indent + TAB;
if (ext.getDirectReference() != null) {
buf.append(tab + "Direct Reference: " + ext.getDirectReference().getId() + nl);
}
if (ext.getIndirectReference() != null) {
buf.append(tab + "Indirect Reference: " + ext.getIndirectReference().toString() + nl);
}
if (ext.getDataValueDescriptor() != null) {
_dumpAsString(tab, verbose, ext.getDataValueDescriptor(), buf);
}
buf.append(tab + "Encoding: " + ext.getEncoding() + nl);
_dumpAsString(tab, verbose, ext.getExternalContent(), buf);
} else {
buf.append(indent + obj.toString() + nl);
}
}
use of org.bouncycastle.asn1.ASN1BMPString in project LinLong-Java by zhenwei1108.
the class PKCS12KeyStoreSpi method createSafeBag.
private SafeBag createSafeBag(String certId, Certificate cert) throws CertificateEncodingException {
CertBag cBag = new CertBag(x509Certificate, new DEROctetString(cert.getEncoded()));
ASN1EncodableVector fName = new ASN1EncodableVector();
boolean cAttrSet = false;
if (cert instanceof PKCS12BagAttributeCarrier) {
PKCS12BagAttributeCarrier bagAttrs = (PKCS12BagAttributeCarrier) cert;
//
// make sure we are using the local alias on store
//
ASN1BMPString nm = (ASN1BMPString) bagAttrs.getBagAttribute(pkcs_9_at_friendlyName);
if (nm == null || !nm.getString().equals(certId)) {
if (certId != null) {
bagAttrs.setBagAttribute(pkcs_9_at_friendlyName, new DERBMPString(certId));
}
}
Enumeration e = bagAttrs.getBagAttributeKeys();
while (e.hasMoreElements()) {
ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) e.nextElement();
// If we find one, we'll prune it out.
if (oid.equals(PKCSObjectIdentifiers.pkcs_9_at_localKeyId)) {
continue;
}
ASN1EncodableVector fSeq = new ASN1EncodableVector();
fSeq.add(oid);
fSeq.add(new DERSet(bagAttrs.getBagAttribute(oid)));
fName.add(new DERSequence(fSeq));
cAttrSet = true;
}
}
if (!cAttrSet) {
ASN1EncodableVector fSeq = new ASN1EncodableVector();
fSeq.add(pkcs_9_at_friendlyName);
fSeq.add(new DERSet(new DERBMPString(certId)));
fName.add(new DERSequence(fSeq));
}
return new SafeBag(certBag, cBag.toASN1Primitive(), new DERSet(fName));
}
use of org.bouncycastle.asn1.ASN1BMPString in project LinLong-Java by zhenwei1108.
the class PKCS12KeyStoreSpi method doStore.
private void doStore(OutputStream stream, char[] password, boolean useDEREncoding) throws IOException {
if (keys.size() == 0) {
if (password == null) {
Enumeration cs = certs.keys();
ASN1EncodableVector certSeq = new ASN1EncodableVector();
while (cs.hasMoreElements()) {
try {
String certId = (String) cs.nextElement();
Certificate cert = (Certificate) certs.get(certId);
SafeBag sBag = createSafeBag(certId, cert);
certSeq.add(sBag);
} catch (CertificateEncodingException e) {
throw new IOException("Error encoding certificate: " + e.toString());
}
}
if (useDEREncoding) {
ContentInfo bagInfo = new ContentInfo(PKCSObjectIdentifiers.data, new DEROctetString(new DERSequence(certSeq).getEncoded()));
Pfx pfx = new Pfx(new ContentInfo(PKCSObjectIdentifiers.data, new DEROctetString(new DERSequence(bagInfo).getEncoded())), null);
pfx.encodeTo(stream, ASN1Encoding.DER);
} else {
ContentInfo bagInfo = new ContentInfo(PKCSObjectIdentifiers.data, new BEROctetString(new BERSequence(certSeq).getEncoded()));
Pfx pfx = new Pfx(new ContentInfo(PKCSObjectIdentifiers.data, new BEROctetString(new BERSequence(bagInfo).getEncoded())), null);
pfx.encodeTo(stream, ASN1Encoding.BER);
}
return;
}
} else {
if (password == null) {
throw new NullPointerException("no password supplied for PKCS#12 KeyStore");
}
}
//
// handle the key
//
ASN1EncodableVector keyS = new ASN1EncodableVector();
Enumeration ks = keys.keys();
while (ks.hasMoreElements()) {
byte[] kSalt = new byte[SALT_SIZE];
random.nextBytes(kSalt);
String name = (String) ks.nextElement();
PrivateKey privKey = (PrivateKey) keys.get(name);
PKCS12PBEParams kParams = new PKCS12PBEParams(kSalt, MIN_ITERATIONS);
byte[] kBytes = wrapKey(keyAlgorithm.getId(), privKey, kParams, password);
AlgorithmIdentifier kAlgId = new AlgorithmIdentifier(keyAlgorithm, kParams.toASN1Primitive());
com.github.zhenwei.core.asn1.pkcs.EncryptedPrivateKeyInfo kInfo = new com.github.zhenwei.core.asn1.pkcs.EncryptedPrivateKeyInfo(kAlgId, kBytes);
boolean attrSet = false;
ASN1EncodableVector kName = new ASN1EncodableVector();
if (privKey instanceof PKCS12BagAttributeCarrier) {
PKCS12BagAttributeCarrier bagAttrs = (PKCS12BagAttributeCarrier) privKey;
//
// make sure we are using the local alias on store
//
ASN1BMPString nm = (ASN1BMPString) bagAttrs.getBagAttribute(pkcs_9_at_friendlyName);
if (nm == null || !nm.getString().equals(name)) {
bagAttrs.setBagAttribute(pkcs_9_at_friendlyName, new DERBMPString(name));
}
//
if (bagAttrs.getBagAttribute(pkcs_9_at_localKeyId) == null) {
Certificate ct = engineGetCertificate(name);
bagAttrs.setBagAttribute(pkcs_9_at_localKeyId, createSubjectKeyId(ct.getPublicKey()));
}
Enumeration e = bagAttrs.getBagAttributeKeys();
while (e.hasMoreElements()) {
ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) e.nextElement();
ASN1EncodableVector kSeq = new ASN1EncodableVector();
kSeq.add(oid);
kSeq.add(new DERSet(bagAttrs.getBagAttribute(oid)));
attrSet = true;
kName.add(new DERSequence(kSeq));
}
}
if (!attrSet) {
//
// set a default friendly name (from the key id) and local id
//
ASN1EncodableVector kSeq = new ASN1EncodableVector();
Certificate ct = engineGetCertificate(name);
kSeq.add(pkcs_9_at_localKeyId);
kSeq.add(new DERSet(createSubjectKeyId(ct.getPublicKey())));
kName.add(new DERSequence(kSeq));
kSeq = new ASN1EncodableVector();
kSeq.add(pkcs_9_at_friendlyName);
kSeq.add(new DERSet(new DERBMPString(name)));
kName.add(new DERSequence(kSeq));
}
SafeBag kBag = new SafeBag(pkcs8ShroudedKeyBag, kInfo.toASN1Primitive(), new DERSet(kName));
keyS.add(kBag);
}
byte[] keySEncoded = new DERSequence(keyS).getEncoded(ASN1Encoding.DER);
BEROctetString keyString = new BEROctetString(keySEncoded);
//
// certificate processing
//
byte[] cSalt = new byte[SALT_SIZE];
random.nextBytes(cSalt);
ASN1EncodableVector certSeq = new ASN1EncodableVector();
PKCS12PBEParams cParams = new PKCS12PBEParams(cSalt, MIN_ITERATIONS);
AlgorithmIdentifier cAlgId = new AlgorithmIdentifier(certAlgorithm, cParams.toASN1Primitive());
Hashtable doneCerts = new Hashtable();
Enumeration cs = keys.keys();
while (cs.hasMoreElements()) {
try {
String name = (String) cs.nextElement();
Certificate cert = engineGetCertificate(name);
boolean cAttrSet = false;
CertBag cBag = new CertBag(x509Certificate, new DEROctetString(cert.getEncoded()));
ASN1EncodableVector fName = new ASN1EncodableVector();
if (cert instanceof PKCS12BagAttributeCarrier) {
PKCS12BagAttributeCarrier bagAttrs = (PKCS12BagAttributeCarrier) cert;
//
// make sure we are using the local alias on store
//
ASN1BMPString nm = (ASN1BMPString) bagAttrs.getBagAttribute(pkcs_9_at_friendlyName);
if (nm == null || !nm.getString().equals(name)) {
bagAttrs.setBagAttribute(pkcs_9_at_friendlyName, new DERBMPString(name));
}
//
if (bagAttrs.getBagAttribute(pkcs_9_at_localKeyId) == null) {
bagAttrs.setBagAttribute(pkcs_9_at_localKeyId, createSubjectKeyId(cert.getPublicKey()));
}
Enumeration e = bagAttrs.getBagAttributeKeys();
while (e.hasMoreElements()) {
ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) e.nextElement();
ASN1EncodableVector fSeq = new ASN1EncodableVector();
fSeq.add(oid);
fSeq.add(new DERSet(bagAttrs.getBagAttribute(oid)));
fName.add(new DERSequence(fSeq));
cAttrSet = true;
}
}
if (!cAttrSet) {
ASN1EncodableVector fSeq = new ASN1EncodableVector();
fSeq.add(pkcs_9_at_localKeyId);
fSeq.add(new DERSet(createSubjectKeyId(cert.getPublicKey())));
fName.add(new DERSequence(fSeq));
fSeq = new ASN1EncodableVector();
fSeq.add(pkcs_9_at_friendlyName);
fSeq.add(new DERSet(new DERBMPString(name)));
fName.add(new DERSequence(fSeq));
}
SafeBag sBag = new SafeBag(certBag, cBag.toASN1Primitive(), new DERSet(fName));
certSeq.add(sBag);
doneCerts.put(cert, cert);
} catch (CertificateEncodingException e) {
throw new IOException("Error encoding certificate: " + e.toString());
}
}
cs = certs.keys();
while (cs.hasMoreElements()) {
try {
String certId = (String) cs.nextElement();
Certificate cert = (Certificate) certs.get(certId);
if (keys.get(certId) != null) {
continue;
}
SafeBag sBag = createSafeBag(certId, cert);
certSeq.add(sBag);
doneCerts.put(cert, cert);
} catch (CertificateEncodingException e) {
throw new IOException("Error encoding certificate: " + e.toString());
}
}
Set usedSet = getUsedCertificateSet();
cs = chainCerts.keys();
while (cs.hasMoreElements()) {
try {
CertId certId = (CertId) cs.nextElement();
Certificate cert = (Certificate) chainCerts.get(certId);
if (!usedSet.contains(cert)) {
continue;
}
if (doneCerts.get(cert) != null) {
continue;
}
CertBag cBag = new CertBag(x509Certificate, new DEROctetString(cert.getEncoded()));
ASN1EncodableVector fName = new ASN1EncodableVector();
if (cert instanceof PKCS12BagAttributeCarrier) {
PKCS12BagAttributeCarrier bagAttrs = (PKCS12BagAttributeCarrier) cert;
Enumeration e = bagAttrs.getBagAttributeKeys();
while (e.hasMoreElements()) {
ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) e.nextElement();
// If we find one, we'll prune it out.
if (oid.equals(PKCSObjectIdentifiers.pkcs_9_at_localKeyId)) {
continue;
}
ASN1EncodableVector fSeq = new ASN1EncodableVector();
fSeq.add(oid);
fSeq.add(new DERSet(bagAttrs.getBagAttribute(oid)));
fName.add(new DERSequence(fSeq));
}
}
SafeBag sBag = new SafeBag(certBag, cBag.toASN1Primitive(), new DERSet(fName));
certSeq.add(sBag);
} catch (CertificateEncodingException e) {
throw new IOException("Error encoding certificate: " + e.toString());
}
}
byte[] certSeqEncoded = new DERSequence(certSeq).getEncoded(ASN1Encoding.DER);
byte[] certBytes = cryptData(true, cAlgId, password, false, certSeqEncoded);
EncryptedData cInfo = new EncryptedData(data, cAlgId, new BEROctetString(certBytes));
ContentInfo[] info = new ContentInfo[] { new ContentInfo(data, keyString), new ContentInfo(encryptedData, cInfo.toASN1Primitive()) };
AuthenticatedSafe auth = new AuthenticatedSafe(info);
byte[] pkg = auth.getEncoded(useDEREncoding ? ASN1Encoding.DER : ASN1Encoding.BER);
ContentInfo mainInfo = new ContentInfo(data, new BEROctetString(pkg));
//
// create the mac
//
byte[] mSalt = new byte[saltLength];
random.nextBytes(mSalt);
byte[] data = ((ASN1OctetString) mainInfo.getContent()).getOctets();
MacData mData;
try {
byte[] res = calculatePbeMac(macAlgorithm.getAlgorithm(), mSalt, itCount, password, false, data);
DigestInfo dInfo = new DigestInfo(macAlgorithm, res);
mData = new MacData(dInfo, mSalt, itCount);
} catch (Exception e) {
throw new IOException("error constructing MAC: " + e.toString());
}
//
// output the Pfx
//
Pfx pfx = new Pfx(mainInfo, mData);
pfx.encodeTo(stream, useDEREncoding ? ASN1Encoding.DER : ASN1Encoding.BER);
}
use of org.bouncycastle.asn1.ASN1BMPString in project LinLong-Java by zhenwei1108.
the class PKCS12KeyStoreSpi method engineLoad.
public void engineLoad(InputStream stream, char[] password) throws IOException {
if (// just initialising
stream == null) {
return;
}
BufferedInputStream bufIn = new BufferedInputStream(stream);
bufIn.mark(10);
int head = bufIn.read();
if (head < 0) {
throw new EOFException("no data in keystore stream");
}
if (head != 0x30) {
throw new IOException("stream does not represent a PKCS12 key store");
}
bufIn.reset();
ASN1InputStream bIn = new ASN1InputStream(bufIn);
Pfx bag;
try {
bag = Pfx.getInstance(bIn.readObject());
} catch (Exception e) {
throw new IOException(e.getMessage());
}
ContentInfo info = bag.getAuthSafe();
Vector chain = new Vector();
boolean unmarkedKey = false;
boolean wrongPKCS12Zero = false;
if (// check the mac code
bag.getMacData() != null) {
if (password == null) {
throw new NullPointerException("no password supplied when one expected");
}
MacData mData = bag.getMacData();
DigestInfo dInfo = mData.getMac();
macAlgorithm = dInfo.getAlgorithmId();
byte[] salt = mData.getSalt();
itCount = validateIterationCount(mData.getIterationCount());
saltLength = salt.length;
byte[] data = ((ASN1OctetString) info.getContent()).getOctets();
try {
byte[] res = calculatePbeMac(macAlgorithm.getAlgorithm(), 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(macAlgorithm.getAlgorithm(), 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());
}
} else if (password != null && password.length != 0) {
if (!Properties.isOverrideSet("com.github.zhenwei.pkix.pkcs12.ignore_useless_passwd")) {
throw new IOException("password supplied for keystore that does not require one");
}
}
keys = new IgnoresCaseHashtable();
localIds = new IgnoresCaseHashtable();
if (info.getContentType().equals(data)) {
ASN1OctetString content = ASN1OctetString.getInstance(info.getContent());
AuthenticatedSafe authSafe = AuthenticatedSafe.getInstance(content.getOctets());
ContentInfo[] c = authSafe.getContentInfo();
for (int i = 0; i != c.length; i++) {
if (c[i].getContentType().equals(data)) {
ASN1OctetString authSafeContent = ASN1OctetString.getInstance(c[i].getContent());
ASN1Sequence seq = ASN1Sequence.getInstance(authSafeContent.getOctets());
for (int j = 0; j != seq.size(); j++) {
SafeBag b = SafeBag.getInstance(seq.getObjectAt(j));
if (b.getBagId().equals(pkcs8ShroudedKeyBag)) {
com.github.zhenwei.core.asn1.pkcs.EncryptedPrivateKeyInfo eIn = com.github.zhenwei.core.asn1.pkcs.EncryptedPrivateKeyInfo.getInstance(b.getBagValue());
PrivateKey privKey = unwrapKey(eIn.getEncryptionAlgorithm(), eIn.getEncryptedData(), password, wrongPKCS12Zero);
//
// set the attributes on the key
//
String alias = null;
ASN1OctetString localId = null;
if (b.getBagAttributes() != null) {
Enumeration e = b.getBagAttributes().getObjects();
while (e.hasMoreElements()) {
ASN1Sequence sq = (ASN1Sequence) e.nextElement();
ASN1ObjectIdentifier aOid = (ASN1ObjectIdentifier) sq.getObjectAt(0);
ASN1Set attrSet = (ASN1Set) sq.getObjectAt(1);
ASN1Primitive attr = null;
if (attrSet.size() > 0) {
attr = (ASN1Primitive) attrSet.getObjectAt(0);
if (privKey instanceof PKCS12BagAttributeCarrier) {
PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) privKey;
ASN1Encodable existing = bagAttr.getBagAttribute(aOid);
if (existing != null) {
// OK, but the value has to be the same
if (!existing.toASN1Primitive().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 = ((ASN1BMPString) 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 = EncryptedData.getInstance(c[i].getContent());
byte[] octets = cryptData(false, d.getEncryptionAlgorithm(), password, wrongPKCS12Zero, d.getContent().getOctets());
ASN1Sequence seq = ASN1Sequence.getInstance(octets);
for (int j = 0; j != seq.size(); j++) {
SafeBag b = SafeBag.getInstance(seq.getObjectAt(j));
if (b.getBagId().equals(certBag)) {
chain.addElement(b);
} else if (b.getBagId().equals(pkcs8ShroudedKeyBag)) {
com.github.zhenwei.core.asn1.pkcs.EncryptedPrivateKeyInfo eIn = com.github.zhenwei.core.asn1.pkcs.EncryptedPrivateKeyInfo.getInstance(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();
ASN1ObjectIdentifier aOid = (ASN1ObjectIdentifier) sq.getObjectAt(0);
ASN1Set attrSet = (ASN1Set) sq.getObjectAt(1);
ASN1Primitive attr = null;
if (attrSet.size() > 0) {
attr = (ASN1Primitive) attrSet.getObjectAt(0);
ASN1Encodable existing = bagAttr.getBagAttribute(aOid);
if (existing != null) {
// OK, but the value has to be the same
if (!existing.toASN1Primitive().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 = ((ASN1BMPString) 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)) {
com.github.zhenwei.core.asn1.pkcs.PrivateKeyInfo kInfo = com.github.zhenwei.core.asn1.pkcs.PrivateKeyInfo.getInstance(b.getBagValue());
PrivateKey privKey = WeGooProvider.getPrivateKey(kInfo);
//
// 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.getInstance(e.nextElement());
ASN1ObjectIdentifier aOid = ASN1ObjectIdentifier.getInstance(sq.getObjectAt(0));
ASN1Set attrSet = ASN1Set.getInstance(sq.getObjectAt(1));
ASN1Primitive attr = null;
if (attrSet.size() > 0) {
attr = (ASN1Primitive) attrSet.getObjectAt(0);
ASN1Encodable existing = bagAttr.getBagAttribute(aOid);
if (existing != null) {
// OK, but the value has to be the same
if (!existing.toASN1Primitive().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 = ((ASN1BMPString) 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 = CertBag.getInstance(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.getInstance(e.nextElement());
ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(sq.getObjectAt(0));
ASN1Set attrSet = ASN1Set.getInstance(sq.getObjectAt(1));
if (// sometimes this is empty!
attrSet.size() > 0) {
ASN1Primitive attr = (ASN1Primitive) attrSet.getObjectAt(0);
PKCS12BagAttributeCarrier bagAttr = null;
if (cert instanceof PKCS12BagAttributeCarrier) {
bagAttr = (PKCS12BagAttributeCarrier) cert;
ASN1Encodable existing = bagAttr.getBagAttribute(oid);
if (existing != null) {
// we've found more than one - one might be incorrect
if (oid.equals(pkcs_9_at_localKeyId)) {
String id = Hex.toHexString(((ASN1OctetString) attr).getOctets());
if (!(keys.keys.containsKey(id) || localIds.keys.containsKey(id))) {
// ignore this one - it's not valid
continue;
}
}
// OK, but the value has to be the same
if (!existing.toASN1Primitive().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 = ((ASN1BMPString) 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);
}
}
}
}
Aggregations