use of org.apache.harmony.security.asn1.ASN1OctetString in project XobotOS by xamarin.
the class JDKPKCS12KeyStore method doStore.
private void doStore(OutputStream stream, char[] password, boolean useDEREncoding) throws IOException {
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.getDERObject());
org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo kInfo = new org.bouncycastle.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
//
DERBMPString nm = (DERBMPString) 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()) {
DERObjectIdentifier oid = (DERObjectIdentifier) 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.getDERObject(), new DERSet(kName));
keyS.add(kBag);
}
byte[] keySEncoded = new DERSequence(keyS).getDEREncoded();
BERConstructedOctetString keyString = new BERConstructedOctetString(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.getDERObject());
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
//
DERBMPString nm = (DERBMPString) 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()) {
DERObjectIdentifier oid = (DERObjectIdentifier) 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.getDERObject(), 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);
boolean cAttrSet = false;
if (keys.get(certId) != null) {
continue;
}
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
//
DERBMPString nm = (DERBMPString) bagAttrs.getBagAttribute(pkcs_9_at_friendlyName);
if (nm == null || !nm.getString().equals(certId)) {
bagAttrs.setBagAttribute(pkcs_9_at_friendlyName, new DERBMPString(certId));
}
Enumeration e = bagAttrs.getBagAttributeKeys();
while (e.hasMoreElements()) {
DERObjectIdentifier oid = (DERObjectIdentifier) 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));
}
SafeBag sBag = new SafeBag(certBag, cBag.getDERObject(), new DERSet(fName));
certSeq.add(sBag);
doneCerts.put(cert, cert);
} catch (CertificateEncodingException e) {
throw new IOException("Error encoding certificate: " + e.toString());
}
}
cs = chainCerts.keys();
while (cs.hasMoreElements()) {
try {
CertId certId = (CertId) cs.nextElement();
Certificate cert = (Certificate) chainCerts.get(certId);
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()) {
DERObjectIdentifier oid = (DERObjectIdentifier) 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.getDERObject(), new DERSet(fName));
certSeq.add(sBag);
} catch (CertificateEncodingException e) {
throw new IOException("Error encoding certificate: " + e.toString());
}
}
byte[] certSeqEncoded = new DERSequence(certSeq).getDEREncoded();
byte[] certBytes = cryptData(true, cAlgId, password, false, certSeqEncoded);
EncryptedData cInfo = new EncryptedData(data, cAlgId, new BERConstructedOctetString(certBytes));
ContentInfo[] info = new ContentInfo[] { new ContentInfo(data, keyString), new ContentInfo(encryptedData, cInfo.getDERObject()) };
AuthenticatedSafe auth = new AuthenticatedSafe(info);
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
DEROutputStream asn1Out;
if (useDEREncoding) {
asn1Out = new DEROutputStream(bOut);
} else {
asn1Out = new BEROutputStream(bOut);
}
asn1Out.writeObject(auth);
byte[] pkg = bOut.toByteArray();
ContentInfo mainInfo = new ContentInfo(data, new BERConstructedOctetString(pkg));
//
// create the mac
//
byte[] mSalt = new byte[20];
int itCount = MIN_ITERATIONS;
random.nextBytes(mSalt);
byte[] data = ((ASN1OctetString) mainInfo.getContent()).getOctets();
MacData mData;
try {
byte[] res = calculatePbeMac(id_SHA1, mSalt, itCount, password, false, data);
// BEGIN android-changed
AlgorithmIdentifier algId = new AlgorithmIdentifier(id_SHA1, DERNull.INSTANCE);
// END android-changed
DigestInfo dInfo = new DigestInfo(algId, 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);
if (useDEREncoding) {
asn1Out = new DEROutputStream(stream);
} else {
asn1Out = new BEROutputStream(stream);
}
asn1Out.writeObject(pfx);
}
use of org.apache.harmony.security.asn1.ASN1OctetString in project XobotOS by xamarin.
the class CertPathValidatorUtilities method getObject.
private static DERObject getObject(String oid, byte[] ext) throws AnnotatedException {
try {
ASN1InputStream aIn = new ASN1InputStream(ext);
ASN1OctetString octs = (ASN1OctetString) aIn.readObject();
aIn = new ASN1InputStream(octs.getOctets());
return aIn.readObject();
} catch (Exception e) {
throw new AnnotatedException("exception processing extension " + oid, e);
}
}
use of org.apache.harmony.security.asn1.ASN1OctetString in project nhin-d by DirectProject.
the class TrustChainValidator method getObject.
private DERObject getObject(byte[] ext) {
ASN1InputStream aIn = null;
try {
aIn = new ASN1InputStream(ext);
ASN1OctetString octs = (ASN1OctetString) aIn.readObject();
IOUtils.closeQuietly(aIn);
aIn = new ASN1InputStream(octs.getOctets());
return aIn.readObject();
} catch (Exception e) {
throw new IllegalArgumentException("Exception processing data ", e);
} finally {
IOUtils.closeQuietly(aIn);
}
}
use of org.apache.harmony.security.asn1.ASN1OctetString in project nhin-d by DirectProject.
the class MessageSigInspector method getObject.
protected static DERObject getObject(byte[] ext) throws PolicyProcessException {
ASN1InputStream aIn = null;
try {
aIn = new ASN1InputStream(ext);
ASN1OctetString octs = (ASN1OctetString) aIn.readObject();
IOUtils.closeQuietly(aIn);
aIn = new ASN1InputStream(octs.getOctets());
return aIn.readObject();
} catch (Exception e) {
throw new PolicyProcessException("Exception processing data ", e);
} finally {
IOUtils.closeQuietly(aIn);
}
}
use of org.apache.harmony.security.asn1.ASN1OctetString 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);
}
}
Aggregations