public static void Pkcs9AttributeObjectNullaryCtor() { Pkcs9AttributeObject p = new Pkcs9AttributeObject(); Assert.Null(p.Oid); Assert.Null(p.RawData); }
public static void Pkcs9AttributeAsnEncodedDataCtorNullOid() { AsnEncodedData a = new AsnEncodedData(new byte[3]); object ign; Assert.Throws <ArgumentNullException>(() => ign = new Pkcs9AttributeObject(a)); }
public void ConstructorEmpty() { Pkcs9AttributeObject a = new Pkcs9AttributeObject(); Assert.IsNull(a.Oid, "Oid"); Assert.IsNull(a.RawData, "RawData"); }
/// <summary> /// Useful helper for "upgrading" well-known CMS attributes to type-specific objects such as Pkcs9DocumentName, Pkcs9DocumentDescription, etc. /// </summary> public static Pkcs9AttributeObject CreateBestPkcs9AttributeObjectAvailable(Oid oid, byte[] encodedAttribute) { Pkcs9AttributeObject attributeObject = new Pkcs9AttributeObject(oid, encodedAttribute); switch (oid.Value) { case Oids.DocumentName: attributeObject = Upgrade <Pkcs9DocumentName>(attributeObject); break; case Oids.DocumentDescription: attributeObject = Upgrade <Pkcs9DocumentDescription>(attributeObject); break; case Oids.SigningTime: attributeObject = Upgrade <Pkcs9SigningTime>(attributeObject); break; case Oids.ContentType: attributeObject = Upgrade <Pkcs9ContentType>(attributeObject); break; case Oids.MessageDigest: attributeObject = Upgrade <Pkcs9MessageDigest>(attributeObject); break; default: break; } return(attributeObject); }
private static T Upgrade <T>(Pkcs9AttributeObject basicAttribute) where T : Pkcs9AttributeObject, new() { T enhancedAttribute = new T(); enhancedAttribute.CopyFrom(basicAttribute); return(enhancedAttribute); }
public void CopyFrom_SigningTime_OidRaw() { Pkcs9SigningTime st = new Pkcs9SigningTime(DateTime.UtcNow); Pkcs9AttributeObject a = new Pkcs9AttributeObject(); a.CopyFrom(new AsnEncodedData(st.Oid, st.RawData)); }
/// <summary> /// Searches the unsigned attributes in the counter signature for a timestamp token. /// </summary> /// <param name="unsignedAttribute"></param> /// <returns></returns> public static IEnumerable <Timestamp> GetTimestampsFromCounterSignature(AsnEncodedData unsignedAttribute) { var timestamps = new List <Timestamp>(); var rfc3161CounterSignature = new Pkcs9AttributeObject(unsignedAttribute); SignedCms rfc3161Message = new SignedCms(); rfc3161Message.Decode(rfc3161CounterSignature.RawData); foreach (SignerInfo rfc3161SignerInfo in rfc3161Message.SignerInfos) { if (String.Equals(rfc3161Message.ContentInfo.ContentType.Value, WinCrypt.szOID_TIMESTAMP_TOKEN, StringComparison.OrdinalIgnoreCase)) { var timestampToken = NuGet.Packaging.Signing.TstInfo.Read(rfc3161Message.ContentInfo.Content); var timeStamp = new Timestamp { SignedOn = timestampToken.GenTime.LocalDateTime, EffectiveDate = Convert.ToDateTime(rfc3161SignerInfo.Certificate.GetEffectiveDateString()).ToLocalTime(), ExpiryDate = Convert.ToDateTime(rfc3161SignerInfo.Certificate.GetExpirationDateString()).ToLocalTime(), SignatureAlgorithm = rfc3161SignerInfo.Certificate.SignatureAlgorithm.FriendlyName }; timestamps.Add(timeStamp); } } return(timestamps); }
public static void TestUnprotectedAttributes1_MessageDigest_RoundTrip() { byte[] rawData = "0405032d58805d".HexToByteArray(); Pkcs9AttributeObject pkcs9MessageDigest = new Pkcs9AttributeObject(Oids.MessageDigest, rawData); byte[] encodedMessage = CreateEcmsWithAttributes(pkcs9MessageDigest); VerifyUnprotectedAttributes1_MessageDigest(encodedMessage); }
public static void TestUnprotectedAttributes1_ContentType_RoundTrip() { byte[] rawData = "06072a9fa20082f300".HexToByteArray(); Pkcs9AttributeObject pkcs9ContentType = new Pkcs9AttributeObject(Oids.ContentType, rawData); byte[] encodedMessage = CreateEcmsWithAttributes(pkcs9ContentType); VerifyUnprotectedAttributes1_ContentType(encodedMessage); }
public void CopyFrom_Self() { Pkcs9AttributeObject a = new Pkcs9AttributeObject("1.2.3.4", new byte[2] { 0x05, 0x00 }); a.CopyFrom(new AsnEncodedData(a.Oid, a.RawData)); }
public void ConstructorStringArray() { Pkcs9AttributeObject a = new Pkcs9AttributeObject(defaultOid, new byte[0]); Assert.AreEqual(defaultName, a.Oid.FriendlyName, "Oid.FriendlyName"); Assert.AreEqual(defaultOid, a.Oid.Value, "Oid.Value"); Assert.AreEqual(0, a.RawData.Length, "RawData"); }
private static Pkcs9ContentType CreatePkcs9ContentType(byte[] rawData) { Pkcs9ContentType pkcs9ContentType = new Pkcs9ContentType(); Pkcs9AttributeObject pkcs9AttributeObject = new Pkcs9AttributeObject(pkcs9ContentType.Oid, rawData); pkcs9ContentType.CopyFrom(pkcs9AttributeObject); return(pkcs9ContentType); }
public static void KeyIdFromRawData(string inputHex, string expectedHex) { var attr = new Pkcs9AttributeObject(Oids.LocalKeyId, inputHex.HexToByteArray()); Pkcs9LocalKeyId localKeyId = new Pkcs9LocalKeyId(); localKeyId.CopyFrom(attr); Assert.Equal(expectedHex, localKeyId.KeyId.ByteArrayToHex()); }
public static void KeyIdFromInvalidData(string invalidHex) { var attr = new Pkcs9AttributeObject(Oids.LocalKeyId, invalidHex.HexToByteArray()); Pkcs9LocalKeyId localKeyId = new Pkcs9LocalKeyId(); localKeyId.CopyFrom(attr); Assert.ThrowsAny <CryptographicException>(() => localKeyId.KeyId); }
public static void Pkcs9AttributeCopyFromAsnNotAPkcs9Attribute() { // Pkcs9AttributeObject.CopyFrom(AsnEncodedData) refuses to accept any AsnEncodedData that isn't a Pkcs9AttributeObject-derived class. Pkcs9AttributeObject p = new Pkcs9AttributeObject(); byte[] rawData = "041e4d00790020004400650073006300720069007000740069006f006e000000".HexToByteArray(); AsnEncodedData a = new AsnEncodedData(Oids.DocumentName, rawData); AssertExtensions.Throws <ArgumentException>(null, () => p.CopyFrom(a)); }
public static void Pkcs9AttributeAsnEncodedDataCtorNullOidValue() { Oid oid = new Oid(Oids.Aes128); oid.Value = null; AsnEncodedData a = new AsnEncodedData(oid, new byte[3]); object ign; Assert.Throws <ArgumentNullException>(() => ign = new Pkcs9AttributeObject(a)); }
public static void Pkcs9AttributeAsnEncodedDataCtorEmptyOidValue() { Oid oid = new Oid(Oids.Aes128); oid.Value = string.Empty; AsnEncodedData a = new AsnEncodedData(oid, new byte[3]); object ign; AssertExtensions.Throws <ArgumentException>("oid.Value", () => ign = new Pkcs9AttributeObject(a)); }
public static void Pkcs9AttributeObjectNullaryCtor() { Pkcs9AttributeObject p = new Pkcs9AttributeObject(); Assert.Null(p.Oid); if (PlatformDetection.IsNetCore) { Assert.Empty(p.RawData); } else { Assert.Null(p.RawData); } }
public static void ContentTypeFromCookedData() { string contentType = "1.3.8473.23.4773.23"; byte[] encodedContentType = "06072bc21917a52517".HexToByteArray(); Pkcs9ContentType p = new Pkcs9ContentType(); Pkcs9AttributeObject pkcs9AttributeObject = new Pkcs9AttributeObject(p.Oid, encodedContentType); p.CopyFrom(pkcs9AttributeObject); string cookedData = p.ContentType.Value; Assert.Equal(contentType, cookedData); string oid = p.Oid.Value; Assert.Equal(s_OidContentType, oid); }
public static void MessageDigestFromRawData() { byte[] messageDigest = { 3, 45, 88, 128, 93 }; List <byte> encodedMessageDigestList = new List <byte>(messageDigest.Length + 2); encodedMessageDigestList.Add(4); encodedMessageDigestList.Add(checked ((byte)(messageDigest.Length))); encodedMessageDigestList.AddRange(messageDigest); byte[] encodedMessageDigest = encodedMessageDigestList.ToArray(); Pkcs9MessageDigest p = new Pkcs9MessageDigest(); Pkcs9AttributeObject pAttribute = new Pkcs9AttributeObject(s_OidMessageDigest, encodedMessageDigest); p.CopyFrom(pAttribute); Assert.Equal <byte>(encodedMessageDigest, p.RawData); Assert.Equal <byte>(messageDigest, p.MessageDigest); string oid = p.Oid.Value; Assert.Equal(s_OidMessageDigest, oid); }
private static byte[] CreateSignedDataPkcs7(byte[] encryptedMessageData, X509Certificate2 localPrivateKey) { // Create the outer envelope, signed with the local private key var signer = new CmsSigner(localPrivateKey) { DigestAlgorithm = Oids.Pkcs.MD5 }; // Message Type (messageType): https://tools.ietf.org/html/draft-nourse-scep-23#section-3.1.1.2 // PKCS#10 request = PKCSReq (19) var messageType = new AsnEncodedData(Oids.Scep.MessageType, DerEncoding.EncodePrintableString("19")); signer.SignedAttributes.Add(messageType); // Tranaction ID (transId): https://tools.ietf.org/html/draft-nourse-scep-23#section-3.1.1.1 var sha = new SHA512Managed(); var hashedKey = sha.ComputeHash(localPrivateKey.GetPublicKey()); var hashedKeyString = Convert.ToBase64String(hashedKey); var transactionId = new Pkcs9AttributeObject(Oids.Scep.TransactionId, DerEncoding.EncodePrintableString(hashedKeyString)); signer.SignedAttributes.Add(transactionId); // Sender Nonce (senderNonce): https://tools.ietf.org/html/draft-nourse-scep-23#section-3.1.1.5 lastSenderNonce = new byte[16]; RNGCryptoServiceProvider.Create().GetBytes(lastSenderNonce); var nonce = new Pkcs9AttributeObject(Oids.Scep.SenderNonce, DerEncoding.EncodeOctet(lastSenderNonce)); signer.SignedAttributes.Add(nonce); // Seems that the oid is not needed for this envelope var signedContent = new ContentInfo(encryptedMessageData); //new Oid("1.2.840.113549.1.7.1", "data"), encryptedMessageData); var signedMessage = new SignedCms(signedContent); signedMessage.ComputeSignature(signer); var encodedMessage = signedMessage.Encode(); return(encodedMessage); }
public static void Pkcs9AttributeCopyFromNullAsn() { Pkcs9AttributeObject p = new Pkcs9AttributeObject(); Assert.Throws <ArgumentNullException>(() => p.CopyFrom(null)); }
public static void ReadIndefiniteEncodingNoMac(int trailingByteCount) { ReadOnlyMemory <byte> source = PadContents(Pkcs12Documents.IndefiniteEncodingNoMac, trailingByteCount); Pkcs12Info info = Pkcs12Info.Decode( source, out int bytesRead, skipCopy: true); Assert.Equal(Pkcs12Documents.IndefiniteEncodingNoMac.Length, bytesRead); Assert.Equal(Pkcs12IntegrityMode.None, info.IntegrityMode); ReadOnlyCollection <Pkcs12SafeContents> safes = info.AuthenticatedSafe; Assert.Equal(2, safes.Count); Pkcs12SafeContents firstSafe = safes[0]; Pkcs12SafeContents secondSafe = safes[1]; Assert.Equal(Pkcs12ConfidentialityMode.None, firstSafe.ConfidentialityMode); Assert.Equal(Pkcs12ConfidentialityMode.None, secondSafe.ConfidentialityMode); Assert.True(firstSafe.IsReadOnly, "firstSafe.IsReadOnly"); Assert.True(secondSafe.IsReadOnly, "secondSafe.IsReadOnly"); Pkcs12SafeBag[] firstContents = firstSafe.GetBags().ToArray(); Pkcs12SafeBag[] secondContents = secondSafe.GetBags().ToArray(); Assert.Equal(1, firstContents.Length); Assert.Equal(1, secondContents.Length); Pkcs12KeyBag keyBag = Assert.IsType <Pkcs12KeyBag>(firstContents[0]); Pkcs12CertBag certBag = Assert.IsType <Pkcs12CertBag>(secondContents[0]); CryptographicAttributeObjectCollection keyBagAttrs = keyBag.Attributes; CryptographicAttributeObjectCollection certBagAttrs = certBag.Attributes; Assert.Equal(2, keyBagAttrs.Count); Assert.Equal(2, certBagAttrs.Count); Assert.Equal(Oids.FriendlyName, keyBagAttrs[0].Oid.Value); Assert.Equal(1, keyBagAttrs[0].Values.Count); Assert.Equal(Oids.LocalKeyId, keyBagAttrs[1].Oid.Value); Assert.Equal(1, keyBagAttrs[1].Values.Count); Pkcs9AttributeObject keyFriendlyName = Assert.IsAssignableFrom <Pkcs9AttributeObject>(keyBagAttrs[0].Values[0]); Pkcs9LocalKeyId keyKeyId = Assert.IsType <Pkcs9LocalKeyId>(keyBagAttrs[1].Values[0]); Assert.Equal(Oids.FriendlyName, certBagAttrs[0].Oid.Value); Assert.Equal(1, certBagAttrs[0].Values.Count); Assert.Equal(Oids.LocalKeyId, certBagAttrs[1].Oid.Value); Assert.Equal(1, certBagAttrs[1].Values.Count); Pkcs9AttributeObject certFriendlyName = Assert.IsAssignableFrom <Pkcs9AttributeObject>(certBagAttrs[0].Values[0]); Pkcs9LocalKeyId certKeyId = Assert.IsType <Pkcs9LocalKeyId>(certBagAttrs[1].Values[0]); // This PFX gave a friendlyName value of "cert" to both the key and the cert. Assert.Equal("1E080063006500720074", keyFriendlyName.RawData.ByteArrayToHex()); Assert.Equal(keyFriendlyName.RawData, certFriendlyName.RawData); // The private key (KeyBag) and the public key (CertBag) are matched from their keyId value. Assert.Equal("0414EDF3D122CF623CF0CFC9CD226261E8415A83E630", keyKeyId.RawData.ByteArrayToHex()); Assert.Equal("EDF3D122CF623CF0CFC9CD226261E8415A83E630", keyKeyId.KeyId.ByteArrayToHex()); Assert.Equal(keyKeyId.RawData, certKeyId.RawData); using (X509Certificate2 cert = certBag.GetCertificate()) using (RSA privateKey = RSA.Create()) using (RSA publicKey = cert.GetRSAPublicKey()) { privateKey.ImportPkcs8PrivateKey(keyBag.Pkcs8PrivateKey.Span, out _); Assert.Equal( publicKey.ExportSubjectPublicKeyInfo().ByteArrayToHex(), privateKey.ExportSubjectPublicKeyInfo().ByteArrayToHex()); } }
public void ConstructorOidNullArray() { Oid o = null; Pkcs9AttributeObject a = new Pkcs9AttributeObject(o, new byte[0]); }
public void ConstructorOidArrayNull() { Oid o = new Oid(defaultOid); Pkcs9AttributeObject a = new Pkcs9AttributeObject(o, null); }
public void ConstructorAsnEncodedDataNull() { Pkcs9AttributeObject a = new Pkcs9AttributeObject(null); }
public static IEnumerable <Timestamp> GetTimestamps(string path) { if (String.IsNullOrEmpty(path)) { return(null); } var timestamps = new List <Timestamp>(); int msgAndCertEncodingType; int msgContentType; int formatType; // NULL indicates that information is unneeded IntPtr certStore = IntPtr.Zero; IntPtr msg = IntPtr.Zero; IntPtr context = IntPtr.Zero; if (!WinCrypt.CryptQueryObject( WinCrypt.CERT_QUERY_OBJECT_FILE, Marshal.StringToHGlobalUni(path), WinCrypt.CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED | WinCrypt.CERT_QUERY_CONTENT_FLAG_PKCS7_UNSIGNED | WinCrypt.CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED, WinCrypt.CERT_QUERY_FORMAT_FLAG_ALL, 0, out msgAndCertEncodingType, out msgContentType, out formatType, ref certStore, ref msg, ref context)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } int cbData = 0; // Passing in NULL to pvData retrieves the size of the encoded message if (!WinCrypt.CryptMsgGetParam(msg, WinCrypt.CMSG_ENCODED_MESSAGE, 0, IntPtr.Zero, ref cbData)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } byte[] vData = new byte[cbData]; if (!WinCrypt.CryptMsgGetParam(msg, WinCrypt.CMSG_ENCODED_MESSAGE, 0, vData, ref cbData)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } var signedCms = new SignedCms(); signedCms.Decode(vData); // Timestamp information can be stored in multiple sections. // A single SHA1 stores the timestamp as a counter sign in the unsigned attributes // Multiple authenticode signatures will store additional information as a nested signature // In the case of SHA2 signatures, we need to find and decode the timestamp token (RFC3161). // Luckily NuGet implemented a proper TST and DER parser to decode this foreach (SignerInfo signerInfo in signedCms.SignerInfos) { foreach (CryptographicAttributeObject unsignedAttribute in signerInfo.UnsignedAttributes) { if (String.Equals(unsignedAttribute.Oid.Value, WinCrypt.szOID_RSA_counterSign, StringComparison.OrdinalIgnoreCase)) { foreach (SignerInfo counterSign in signerInfo.CounterSignerInfos) { foreach (CryptographicAttributeObject signedAttribute in counterSign.SignedAttributes) { if (String.Equals(signedAttribute.Oid.Value, WinCrypt.szOID_RSA_signingTime, StringComparison.OrdinalIgnoreCase)) { var st = (Pkcs9SigningTime)signedAttribute.Values[0]; X509Certificate2 cert = counterSign.Certificate; var timeStamp = new Timestamp { SignedOn = st.SigningTime.ToLocalTime(), EffectiveDate = Convert.ToDateTime(cert.GetEffectiveDateString()).ToLocalTime(), ExpiryDate = Convert.ToDateTime(cert.GetExpirationDateString()).ToLocalTime(), SignatureAlgorithm = cert.SignatureAlgorithm.FriendlyName }; timestamps.Add(timeStamp); } } } } else if (String.Equals(unsignedAttribute.Oid.Value, WinCrypt.szOID_RFC3161_counterSign, StringComparison.OrdinalIgnoreCase)) { timestamps.AddRange(GetTimestampsFromCounterSignature(unsignedAttribute.Values[0])); } else if (String.Equals(unsignedAttribute.Oid.Value, WinCrypt.szOID_NESTED_SIGNATURE, StringComparison.OrdinalIgnoreCase)) { var nestedSignature = new Pkcs9AttributeObject(unsignedAttribute.Values[0]); SignedCms nestedSignatureMessage = new SignedCms(); nestedSignatureMessage.Decode(nestedSignature.RawData); foreach (SignerInfo nestedSignerInfo in nestedSignatureMessage.SignerInfos) { foreach (CryptographicAttributeObject nestedUnsignedAttribute in nestedSignerInfo.UnsignedAttributes) { if (String.Equals(nestedUnsignedAttribute.Oid.Value, WinCrypt.szOID_RFC3161_counterSign, StringComparison.OrdinalIgnoreCase)) { timestamps.AddRange(GetTimestampsFromCounterSignature(nestedUnsignedAttribute.Values[0])); } } } } } } return(timestamps); }
/// <summary> /// Verify the signature file, e.g. x.SF using the corresponding signature block, e.g. x.RSA /// </summary> /// <returns>True if the verification is successful, false otherwise.</returns> private bool VerifySignatureRsa() { Timestamps.Clear(); byte[] signatureBlockBytes = JarUtils.ReadBytes(ArchivePath, SignatureBlockFilePath); byte[] signatureFileBytes = JarUtils.ReadBytes(ArchivePath, SignatureFilePath); SHA256Managed sha = new SHA256Managed(); byte[] hash = sha.ComputeHash(signatureFileBytes); ContentInfo ci = new ContentInfo(signatureFileBytes); SignedCms cms = new SignedCms(ci, detached: true); cms.Decode(signatureBlockBytes); try { cms.CheckSignature(verifySignatureOnly: true); // See if we can retrieve a timestamp foreach (SignerInfo signerInfo in cms.SignerInfos) { foreach (CryptographicAttributeObject unsignedAttribute in signerInfo.UnsignedAttributes) { if (String.Equals(unsignedAttribute.Oid.Value, WinCrypt.szOID_SIGNATURE_TIMESTAMP_ATTRIBUTE, StringComparison.OrdinalIgnoreCase)) { Pkcs9AttributeObject timestampAttribute = new Pkcs9AttributeObject(unsignedAttribute.Values[0]); SignedCms timestampCms = new SignedCms(); timestampCms.Decode(timestampAttribute.RawData); TstInfo timestampToken = TstInfo.Read(timestampCms.ContentInfo.Content); foreach (SignerInfo timestampSigner in timestampCms.SignerInfos) { foreach (CryptographicAttributeObject sa in timestampSigner.SignedAttributes) { if (String.Equals(sa.Oid.Value, WinCrypt.szOID_RSA_signingTime, StringComparison.OrdinalIgnoreCase)) { var signingTime = (Pkcs9SigningTime)sa.Values[0]; X509Certificate2 timestampSignerCert = timestampSigner.Certificate; Timestamps.Add(new Timestamp { SignedOn = signingTime.SigningTime.ToLocalTime(), EffectiveDate = Convert.ToDateTime(timestampSignerCert.GetEffectiveDateString()).ToLocalTime(), ExpiryDate = Convert.ToDateTime(timestampSignerCert.GetExpirationDateString()).ToLocalTime(), SignatureAlgorithm = timestampSignerCert.SignatureAlgorithm.FriendlyName }); } } } } } } } catch (CryptographicException ce) { JarError.AddError(ce.Message); return(false); } // If there were no exceptions logged then signature verification should be good. return(true); }
public void ConstructorStringNullArray() { string s = null; Pkcs9AttributeObject a = new Pkcs9AttributeObject(s, new byte[0]); }
public void ConstructorStringArrayNull() { Pkcs9AttributeObject a = new Pkcs9AttributeObject(defaultOid, null); }