How to create a minimal dummy X509Certificate2?

前端 未结 4 1938
暖寄归人
暖寄归人 2021-01-01 11:29

I\'m unit testing a .NET application; some of the unit tests involve programmatically generating X509Certificate2 objects.

I don\'t care about actual signing/private

4条回答
  •  时光取名叫无心
    2021-01-01 12:18

    This may seem very hacky, and it depends on how pragmatic you want to be ... an approach I used was to just grab a random certificate from the machine.

    This was good when: - I know that every machine that's running these tests has a valid certificate. - I was using GIT and didn't want to check in a binary file for the cert - I don't care about the cert content - I'm using code that's not mock friendly and explicitly requires a non-mockable X509Certificate object.

    Definitely not bullet proof, but unblocked me and unblocked my testing scenario.

        static X509Certificate2 GetRandomCertificate()
        {
            X509Store st = new X509Store(StoreName.My, StoreLocation.LocalMachine);
            st.Open(OpenFlags.ReadOnly);
            try
            {
                var certCollection = st.Certificates;
    
                if (certCollection.Count == 0)
                {
                    return null;
                }
                return certCollection[0];
            }
            finally
            {
                st.Close();
            }
        }
    

提交回复
热议问题