use of com.unboundid.asn1.ASN1Set in project LinLong-Java by zhenwei1108.
the class CMSSignedData method getSignerInfos.
/**
* return the collection of signers that are associated with the signatures for the message.
*/
public SignerInformationStore getSignerInfos() {
if (signerInfoStore == null) {
ASN1Set s = signedData.getSignerInfos();
List signerInfos = new ArrayList();
for (int i = 0; i != s.size(); i++) {
SignerInfo info = SignerInfo.getInstance(s.getObjectAt(i));
ASN1ObjectIdentifier contentType = signedData.getEncapContentInfo().getContentType();
if (hashes == null) {
signerInfos.add(new SignerInformation(info, contentType, signedContent, null));
} else {
Object obj = hashes.keySet().iterator().next();
byte[] hash = (obj instanceof String) ? (byte[]) hashes.get(info.getDigestAlgorithm().getAlgorithm().getId()) : (byte[]) hashes.get(info.getDigestAlgorithm().getAlgorithm());
signerInfos.add(new SignerInformation(info, contentType, null, hash));
}
}
signerInfoStore = new SignerInformationStore(signerInfos);
}
return signerInfoStore;
}
use of com.unboundid.asn1.ASN1Set in project LinLong-Java by zhenwei1108.
the class CMSSignedData method addDigestAlgorithm.
/**
* Return a new CMSSignedData which guarantees to have the passed in digestAlgorithm in it.
*
* @param signedData the signed data object to be used as a base.
* @param digestAlgorithm the digest algorithm to be added to the signed data.
* @return a new signed data object.
*/
public static CMSSignedData addDigestAlgorithm(CMSSignedData signedData, AlgorithmIdentifier digestAlgorithm) {
Set<AlgorithmIdentifier> digestAlgorithms = signedData.getDigestAlgorithmIDs();
AlgorithmIdentifier digestAlg = CMSSignedHelper.INSTANCE.fixDigestAlgID(digestAlgorithm, dgstAlgFinder);
//
if (digestAlgorithms.contains(digestAlg)) {
return signedData;
}
//
// copy
//
CMSSignedData cms = new CMSSignedData(signedData);
//
// build up the new set
//
Set<AlgorithmIdentifier> digestAlgs = new HashSet<AlgorithmIdentifier>();
Iterator it = digestAlgorithms.iterator();
while (it.hasNext()) {
digestAlgs.add(CMSSignedHelper.INSTANCE.fixDigestAlgID((AlgorithmIdentifier) it.next(), dgstAlgFinder));
}
digestAlgs.add(digestAlg);
ASN1Set digests = CMSUtils.convertToBERSet(digestAlgs);
ASN1Sequence sD = (ASN1Sequence) signedData.signedData.toASN1Primitive();
ASN1EncodableVector vec = new ASN1EncodableVector();
//
// signers are the last item in the sequence.
//
// version
vec.add(sD.getObjectAt(0));
vec.add(digests);
for (int i = 2; i != sD.size(); i++) {
vec.add(sD.getObjectAt(i));
}
cms.signedData = SignedData.getInstance(new BERSequence(vec));
//
// replace the contentInfo with the new one
//
cms.contentInfo = new ContentInfo(cms.contentInfo.getContentType(), cms.signedData);
return cms;
}
use of com.unboundid.asn1.ASN1Set in project LinLong-Java by zhenwei1108.
the class CMSSignedDataGenerator method generate.
/**
* Generate a CMS Signed Data object which can be carrying a detached CMS signature, or have
* encapsulated data, depending on the value of the encapsulated parameter.
*
* @param content the content to be signed.
* @param encapsulate true if the content should be encapsulated in the signature, false
* otherwise.
*/
public CMSSignedData generate(// FIXME Avoid accessing more than once to support CMSProcessableInputStream
CMSTypedData content, boolean encapsulate) throws CMSException {
if (!signerInfs.isEmpty()) {
throw new IllegalStateException("this method can only be used with SignerInfoGenerator");
}
// TODO
// if (signerInfs.isEmpty())
// {
// /* RFC 3852 5.2
// * "In the degenerate case where there are no signers, the
// * EncapsulatedContentInfo value being "signed" is irrelevant. In this
// * case, the content type within the EncapsulatedContentInfo value being
// * "signed" MUST be id-data (as defined in section 4), and the content
// * field of the EncapsulatedContentInfo value MUST be omitted."
// */
// if (encapsulate)
// {
// throw new IllegalArgumentException("no signers, encapsulate must be false");
// }
// if (!DATA.equals(eContentType))
// {
// throw new IllegalArgumentException("no signers, eContentType must be id-data");
// }
// }
//
// if (!DATA.equals(eContentType))
// {
// /* RFC 3852 5.3
// * [The 'signedAttrs']...
// * field is optional, but it MUST be present if the content type of
// * the EncapsulatedContentInfo value being signed is not id-data.
// */
// // TODO signedAttrs must be present for all signers
// }
Set<AlgorithmIdentifier> digestAlgs = new LinkedHashSet<AlgorithmIdentifier>();
ASN1EncodableVector signerInfos = new ASN1EncodableVector();
// clear the current preserved digest state
digests.clear();
//
for (Iterator it = _signers.iterator(); it.hasNext(); ) {
SignerInformation signer = (SignerInformation) it.next();
CMSUtils.addDigestAlgs(digestAlgs, signer, digestAlgIdFinder);
// TODO Verify the content type and calculated digest match the precalculated SignerInfo
signerInfos.add(signer.toASN1Structure());
}
//
// add the SignerInfo objects
//
ASN1ObjectIdentifier contentTypeOID = content.getContentType();
ASN1OctetString octs = null;
if (content.getContent() != null) {
ByteArrayOutputStream bOut = null;
if (encapsulate) {
bOut = new ByteArrayOutputStream();
}
OutputStream cOut = CMSUtils.attachSignersToOutputStream(signerGens, bOut);
// Just in case it's unencapsulated and there are no signers!
cOut = CMSUtils.getSafeOutputStream(cOut);
try {
content.write(cOut);
cOut.close();
} catch (IOException e) {
throw new CMSException("data processing exception: " + e.getMessage(), e);
}
if (encapsulate) {
octs = new BEROctetString(bOut.toByteArray());
}
}
for (Iterator it = signerGens.iterator(); it.hasNext(); ) {
SignerInfoGenerator sGen = (SignerInfoGenerator) it.next();
SignerInfo inf = sGen.generate(contentTypeOID);
digestAlgs.add(inf.getDigestAlgorithm());
signerInfos.add(inf);
byte[] calcDigest = sGen.getCalculatedDigest();
if (calcDigest != null) {
digests.put(inf.getDigestAlgorithm().getAlgorithm().getId(), calcDigest);
}
}
ASN1Set certificates = null;
if (certs.size() != 0) {
certificates = CMSUtils.createBerSetFromList(certs);
}
ASN1Set certrevlist = null;
if (crls.size() != 0) {
certrevlist = CMSUtils.createBerSetFromList(crls);
}
ContentInfo encInfo = new ContentInfo(contentTypeOID, octs);
SignedData sd = new SignedData(CMSUtils.convertToBERSet(digestAlgs), encInfo, certificates, certrevlist, new DERSet(signerInfos));
ContentInfo contentInfo = new ContentInfo(CMSObjectIdentifiers.signedData, sd);
return new CMSSignedData(content, contentInfo);
}
use of com.unboundid.asn1.ASN1Set in project LinLong-Java by zhenwei1108.
the class CMSAuthenticatedDataGenerator method generate.
/**
* Generate an authenticated data object from the passed in typedData and MacCalculator.
*
* @param typedData the data to have a MAC attached.
* @param macCalculator the calculator of the MAC to be attached.
* @param digestCalculator calculator for computing digest of the encapsulated data.
* @return the resulting CMSAuthenticatedData object.
* @throws CMSException on failure in encoding data or processing recipients.
*/
public CMSAuthenticatedData generate(CMSTypedData typedData, MacCalculator macCalculator, final DigestCalculator digestCalculator) throws CMSException {
ASN1EncodableVector recipientInfos = new ASN1EncodableVector();
ASN1OctetString encContent;
ASN1OctetString macResult;
for (Iterator it = recipientInfoGenerators.iterator(); it.hasNext(); ) {
RecipientInfoGenerator recipient = (RecipientInfoGenerator) it.next();
recipientInfos.add(recipient.generate(macCalculator.getKey()));
}
AuthenticatedData authData;
if (digestCalculator != null) {
try {
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
OutputStream out = new TeeOutputStream(digestCalculator.getOutputStream(), bOut);
typedData.write(out);
out.close();
encContent = new BEROctetString(bOut.toByteArray());
} catch (IOException e) {
throw new CMSException("unable to perform digest calculation: " + e.getMessage(), e);
}
Map parameters = Collections.unmodifiableMap(getBaseParameters(typedData.getContentType(), digestCalculator.getAlgorithmIdentifier(), macCalculator.getAlgorithmIdentifier(), digestCalculator.getDigest()));
if (authGen == null) {
authGen = new DefaultAuthenticatedAttributeTableGenerator();
}
ASN1Set authed = new DERSet(authGen.getAttributes(parameters).toASN1EncodableVector());
try {
OutputStream mOut = macCalculator.getOutputStream();
mOut.write(authed.getEncoded(ASN1Encoding.DER));
mOut.close();
macResult = new DEROctetString(macCalculator.getMac());
} catch (IOException e) {
throw new CMSException("unable to perform MAC calculation: " + e.getMessage(), e);
}
ASN1Set unauthed = (unauthGen != null) ? new BERSet(unauthGen.getAttributes(parameters).toASN1EncodableVector()) : null;
ContentInfo eci = new ContentInfo(typedData.getContentType(), encContent);
authData = new AuthenticatedData(originatorInfo, new DERSet(recipientInfos), macCalculator.getAlgorithmIdentifier(), digestCalculator.getAlgorithmIdentifier(), eci, authed, macResult, unauthed);
} else {
try {
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
OutputStream mOut = new TeeOutputStream(bOut, macCalculator.getOutputStream());
typedData.write(mOut);
mOut.close();
encContent = new BEROctetString(bOut.toByteArray());
macResult = new DEROctetString(macCalculator.getMac());
} catch (IOException e) {
throw new CMSException("unable to perform MAC calculation: " + e.getMessage(), e);
}
ASN1Set unauthed = (unauthGen != null) ? new BERSet(unauthGen.getAttributes(Collections.EMPTY_MAP).toASN1EncodableVector()) : null;
ContentInfo eci = new ContentInfo(typedData.getContentType(), encContent);
authData = new AuthenticatedData(originatorInfo, new DERSet(recipientInfos), macCalculator.getAlgorithmIdentifier(), null, eci, null, macResult, unauthed);
}
ContentInfo contentInfo = new ContentInfo(CMSObjectIdentifiers.authenticatedData, authData);
return new CMSAuthenticatedData(contentInfo, new DigestCalculatorProvider() {
public DigestCalculator get(AlgorithmIdentifier digestAlgorithmIdentifier) throws OperatorCreationException {
return digestCalculator;
}
});
}
use of com.unboundid.asn1.ASN1Set 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