コード例 #1
0
        public byte[] Encode()
        {
            if (this.Elements == null || !this.Elements.Any())
            {
                throw new NotSupportedException("Sequence is null or contains no elements");
            }

            var asn1objs = new List <Asn1Object>();

            foreach (var element in this.Elements)
            {
                if (element.GetType() == typeof(ASN1OctetString))
                {
                    asn1objs.Add(new DerOctetString(element.GetBytes()));
                }
                else if (element.GetType() == typeof(ASN1Integer))
                {
                    asn1objs.Add(new DerInteger(((ASN1Integer)element).Value));
                }
                else
                {
                    throw new NotSupportedException("Sequence contains unsupported element type");
                }
            }

            var derSequence = new DerSequence(asn1objs.ToArray());

            return(derSequence.GetDerEncoded());// .GetDerEncoded();
        }
コード例 #2
0
        private void VerifySignature(byte[] DataToSign, byte[] signature)
        {
            // verify signature
            WriteText("start verify signature");

            // get public key from seal certificate
            var p    = new Org.BouncyCastle.X509.X509CertificateParser();
            var x509 = p.ReadCertificate(seal_cert);

            // return value of signature is juse r and s buffers appended
            // for bouncycastle VerifySignature to work we need an ASN1 Sequence
            int         len                 = signature.Length / 2;
            BigInteger  sssrVal             = new BigInteger(signature, 0, len);
            BigInteger  rVal                = new BigInteger(1, signature, 0, len);
            BigInteger  sssVal              = new BigInteger(signature, len, len);
            BigInteger  sVal                = new BigInteger(1, signature, len, len);
            DerSequence seq                 = new DerSequence(new DerInteger(rVal), new DerInteger(sVal));
            var         signatureAsSequence = seq.GetDerEncoded();

            // actual verify
            ISigner signer = SignerUtilities.GetSigner("SHA256withECDSA");

            signer.Init(false, x509.GetPublicKey());
            signer.BlockUpdate(DataToSign, 0, DataToSign.Length);
            bool result = signer.VerifySignature(signatureAsSequence);

            WriteText("signature verification = " + result.ToString());
        }
コード例 #3
0
        private byte[] generateVIDHash(byte[] randomNum, string idn, string oid)
        {
            // HashContent ::= SEQEUNCE {idn PrintableString, randomNum BIT_STRING }
            DerSequence sequence = new DerSequence(new DerPrintableString(idn), new DerBitString(randomNum));

            return(doubleHash(sequence.GetDerEncoded(), oid));
        }
コード例 #4
0
        public byte[] Encode()
        {
            var digestoid = TransportParameters.DigestParamSet;
            var s         = new DerSequence(
                new DerSequence(
                    new DerOctetString(SessionEncryptedKey.EncryptedKey),
                    new DerOctetString(SessionEncryptedKey.Mac)
                    ),
                new DerTaggedObject(false, 0, new DerSequence(
                                        new DerObjectIdentifier(SessionEncryptedKey.EncryptionParamSet),
                                        new DerTaggedObject(false, 0, new DerSequence(
                                                                new DerSequence(
                                                                    new DerObjectIdentifier(digestoid == Constants.OID_GR3411_12_256 ? Constants.OID_GR3410_12_256 :
                                                                                            digestoid == Constants.OID_GR3411_12_512 ? Constants.OID_GR3410_12_512 :
                                                                                            Constants.OID_GR3410_2001),
                                                                    new DerSequence(
                                                                        new DerObjectIdentifier(TransportParameters.PublicKeyParamSet),
                                                                        new DerObjectIdentifier(TransportParameters.DigestParamSet)                        /*,
                                                                                                                                                            * TransportParameters.EncryptionParamSet != null ?
                                                                                                                                                            * new DerObjectIdentifier(TransportParameters.EncryptionParamSet) : null*/
                                                                        )
                                                                    ),
                                                                new DerBitString(new DerOctetString(TransportParameters.PublicKey))
                                                                )),
                                        new DerOctetString(SessionEncryptedKey.Ukm)
                                        ))
                );

            return(s.GetDerEncoded());
        }
コード例 #5
0
        public byte[] Encode()
        {
            byte[] data;

            try
            {
                var s = new DerSequence(
                    new DerSequence(
                        new DerOctetString(EncryptedKey),
                        new DerOctetString(Mac)
                        ),
                    new DerSequence(
                        new DerObjectIdentifier(EncryptionParamSet),
                        new DerOctetString(Ukm)
                        )
                    );
                data = s.GetDerEncoded();
            }
            catch (Exception exception)
            {
                throw ExceptionUtility.CryptographicException(exception, Resources.Asn1DecodeError, "GostR3410KeyEncode");
            }

            return(data);
        }
コード例 #6
0
        public virtual int GenerateBytes(byte[] outBytes, int outOff, int len)
        {
            DerSequence derSequence = new DerSequence(new AlgorithmIdentifier(algorithm, DerNull.Instance), new DerTaggedObject(explicitly: true, 2, new DerOctetString(Pack.UInt32_To_BE((uint)keySize))));

            kdf.Init(new KdfParameters(z, derSequence.GetDerEncoded()));
            return(kdf.GenerateBytes(outBytes, outOff, len));
        }
コード例 #7
0
        public override bool VerifySignature(byte[] signature)
        {
            int sz  = signature.Length / 2;
            var r   = new BigInteger(1, signature, 0, sz);
            var s   = new BigInteger(1, signature, sz, sz);
            var seq = new DerSequence(new DerInteger(r), new DerInteger(s));

            return(base.VerifySignature(seq.GetDerEncoded()));
        }
コード例 #8
0
        public void Read_WithInvalidHashedMessage_Throws()
        {
            var bcAlgorithmIdentifier = new BcAlgorithmIdentifier(new DerObjectIdentifier(Oids.Sha256));
            var bcMessageImprint      = new DerSequence(bcAlgorithmIdentifier, new DerOctetString(new byte[0]));
            var bytes = bcMessageImprint.GetDerEncoded();

            var exception = Assert.Throws <CryptographicException>(() => MessageImprint.Read(bytes));

            Assert.Equal("The ASN.1 data is invalid.", exception.Message);
        }
コード例 #9
0
        public void Read_WithInvalidSeconds_Throws()
        {
            var bcAccuracy = new DerSequence(new DerInteger(-1));
            var bytes      = bcAccuracy.GetDerEncoded();

            var exception = Assert.Throws <CryptographicException>(
                () => Accuracy.Read(bytes));

            Assert.Equal("The ASN.1 data is invalid.", exception.Message);
        }
コード例 #10
0
        public int GenerateBytes(byte[] outBytes, int outOff, int len)
        {
            // TODO Create an ASN.1 class for this (RFC3278)
            // ECC-CMS-SharedInfo
            var s = new DerSequence(
                new AlgorithmIdentifier(_algorithm, DerNull.Instance),
                new DerTaggedObject(true, 2, new DerOctetString(IntegerToBytes(_keySize))));

            _kdf.Init(new KdfParameters(_z, s.GetDerEncoded()));

            return(_kdf.GenerateBytes(outBytes, outOff, len));
        }
コード例 #11
0
        public virtual int GenerateBytes(byte[] outBytes, int outOff, int len)
        {
            // TODO Create an ASN.1 class for this (RFC3278)
            // ECC-CMS-SharedInfo
            DerSequence s = new DerSequence(
                new AlgorithmIdentifier(algorithm, DerNull.Instance),
                new DerTaggedObject(true, 2, new DerOctetString(Pack.UInt32_To_BE((uint)keySize))));

            kdf.Init(new KdfParameters(z, s.GetDerEncoded()));

            return(kdf.GenerateBytes(outBytes, outOff, len));
        }
コード例 #12
0
        /// <summary>
        /// Encode raw public key assume secp256r1
        /// </summary>
        public static string EncodePublicKey(byte[] publicKey)
        {
            DerSequence pKey = new DerSequence(
                new DerSequence(
                    new DerObjectIdentifier("1.2.840.10045.2.1"),
                    new DerObjectIdentifier("1.2.840.10045.3.1.7")
                    ),
                new DerBitString(publicKey)
                );

            return(Hex.ToHexString(pKey.GetDerEncoded()));
        }
コード例 #13
0
        /// <summary>
        /// Encode private key assume secp256r1
        /// </summary>
        public static string EncodePrviateKey(byte[] publicKey, byte[] privateKey)
        {
            // repack DER
            DerSequence seq = new DerSequence(
                new DerInteger(1),
                new DerOctetString(privateKey),
                new DerTaggedObject(0, new DerObjectIdentifier("1.2.840.10045.3.1.7")),
                new DerTaggedObject(1, new DerBitString(publicKey))
                );

            byte[] der = seq.GetDerEncoded();
            return(Hex.ToHexString(der));
        }
コード例 #14
0
        private static byte[] EncodeSignature(byte[] signature, int keySize)
        {
            byte[] r = new byte[keySize];
            byte[] s = new byte[keySize];
            Array.Copy(signature, 0, r, 0, keySize);
            Array.Copy(signature, keySize, s, 0, keySize);

            var ri  = new DerInteger(new BigInteger(1, r));
            var si  = new DerInteger(new BigInteger(1, s));
            var seq = new DerSequence(ri, si);

            return(seq.GetDerEncoded());
        }
コード例 #15
0
        public void Read_WithValidInput_ReturnsInstance()
        {
            var packageOwners = new[] { "a", "b", "c" };
            var sequence      = new DerSequence(
                new DerUtf8String("a"),
                new DerUtf8String("b"),
                new DerUtf8String("c"));
            var bytes = sequence.GetDerEncoded();

            var nugetPackageOwners = NuGetPackageOwners.Read(bytes);

            Assert.Equal(packageOwners, nugetPackageOwners.PackageOwners);
        }
コード例 #16
0
        public void Read_WithInvalidMicroseconds_Throws(int microseconds)
        {
            var derMicroseconds = new DerTaggedObject(
                explicitly: false,
                tagNo: 1,
                obj: new DerInteger(BigInteger.ValueOf(microseconds)));
            var bcAccuracy = new DerSequence(derMicroseconds);
            var bytes      = bcAccuracy.GetDerEncoded();

            var exception = Assert.Throws <CryptographicException>(
                () => Accuracy.Read(bytes));

            Assert.Equal("The ASN.1 data is invalid.", exception.Message);
        }
コード例 #17
0
        public int GenerateBytes(
            byte[]  outBytes,
            int outOff,
            int len)
        {
            // ECC-CMS-SharedInfo
            DerSequence s = new DerSequence(
                new AlgorithmIdentifier(algorithm, DerNull.Instance),
                new DerTaggedObject(true, 2, new DerOctetString(integerToBytes(keySize))));

            kdf.Init(new KdfParameters(z, s.GetDerEncoded()));

            return(kdf.GenerateBytes(outBytes, outOff, len));
        }
コード例 #18
0
        internal static ECPublicKeyParameters GetECPublicKeyParameters(byte[] publicKey)
        {
            Asn1Object derSequence = new DerSequence(
                new DerSequence(new DerObjectIdentifier(PUBLIC_DER_IDENTIFIER), new DerObjectIdentifier(PRIVATE_DER_IDENTIFIER)),
                new DerBitString(publicKey)
                );

            string pemKey = PUBLIC_PEM_KEY_PREFIX
                            + Convert.ToBase64String(derSequence.GetDerEncoded())
                            + PUBLIC_PEM_KEY_SUFFIX;

            PemReader pemKeyReader = new PemReader(new StringReader(pemKey));

            return((ECPublicKeyParameters)pemKeyReader.ReadObject());
        }
コード例 #19
0
        public void Encode_ReturnsValidDer()
        {
            var packageOwners = new[] { "a", "b", "c" };

            var sequence = new DerSequence(
                new DerUtf8String("a"),
                new DerUtf8String("b"),
                new DerUtf8String("c"));
            var expectedBytes      = sequence.GetDerEncoded();
            var nugetPackageOwners = new NuGetPackageOwners(packageOwners);

            var actualBytes = nugetPackageOwners.Encode();

            Assert.Equal(expectedBytes, actualBytes);
        }
コード例 #20
0
        private byte[] SignBytesDsa(byte[] byteArray, string pathToPrivateKeyPemFile)
        {
            // Create a digest of nonce + cnonce
            // This only seems to work with SHA1 (SHA256 gives us a 401 error)
            var sha    = SHA1.Create();
            var digest = sha.ComputeHash(byteArray);

            // Read DSA key
            DsaKeyParameters keyParameters;

            using (var fileStream = System.IO.File.OpenText(pathToPrivateKeyPemFile))
            {
                var pemReader = new PemReader(fileStream);
                keyParameters = (DsaKeyParameters)pemReader.ReadObject();
            }

            // Create DSA signer
            DsaSigner sig = new DsaSigner();

            sig.Init(true, keyParameters);

            // Digitally sign the digest with our private key
            // The corresponding public key is in our admin handle on the server
            var signature = sig.GenerateSignature(digest);

            // Signature bytes from a DSA key need to be DER-encoded
            // This signature is in two parts (r and s)
            DerSequence seq = new DerSequence(new Asn1Encodable[2] {
                new DerInteger(signature[0]), new DerInteger(signature[1])
            });
            var encode    = seq.GetEncoded();
            var derEncode = seq.GetDerEncoded();


            return(seq.GetDerEncoded());
        }
コード例 #21
0
        public void Read_WithFalseDefaultForCritical_ReturnsInstance()
        {
            var bcExtensions = new DerSequence(
                new DerSequence(new DerObjectIdentifier(_oid.Value), new DerOctetString(_value)));
            var bytes = bcExtensions.GetDerEncoded();

            var extensions = Extensions.Read(bytes);

            Assert.Equal(1, extensions.ExtensionsList.Count);

            var extension = extensions.ExtensionsList[0];

            Assert.Equal(_oid.Value, extension.Id.Value);
            Assert.False(extension.Critical);
            Assert.Equal(_value, extension.Value);
        }
コード例 #22
0
        internal static ECPrivateKeyParameters GetECPrivateKeyParameters(byte[] privateKey)
        {
            Asn1Object derSequence = new DerSequence(
                new DerInteger(1),
                new DerOctetString(privateKey),
                new DerTaggedObject(0, new DerObjectIdentifier(PRIVATE_DER_IDENTIFIER))
                );

            string pemKey = PRIVATE_PEM_KEY_PREFIX
                            + Convert.ToBase64String(derSequence.GetDerEncoded())
                            + PRIVATE_PEM_KEY_SUFFIX;

            PemReader pemKeyReader          = new PemReader(new StringReader(pemKey));
            AsymmetricCipherKeyPair keyPair = (AsymmetricCipherKeyPair)pemKeyReader.ReadObject();

            return((ECPrivateKeyParameters)keyPair.Private);
        }
コード例 #23
0
        public virtual byte[] Encrypt(string password, byte[] salt, int iterationCount, byte[] content)
        {
            AsymmetricKeyParameter asymmetricKey = PrivateKeyFactory.CreateKey(content);

            byte[] encryptedContent = PrivateKeyFactory.EncryptKey(BCObjectIdentifiers.bc_pbe_sha256_pkcs12_aes256_cbc, password.ToCharArray(), salt, iterationCount, asymmetricKey);

            var encryptedKeyPrimitives = (DerSequence)Asn1Object.FromByteArray(encryptedContent);
            var derPrimitives          = new[]
            {
                new DerSequence(new DerObjectIdentifier(BCObjectIdentifiers.bc_pbe_sha256_pkcs12_aes256_cbc.Id),
                                ((DerSequence)encryptedKeyPrimitives[0])[1]),
                encryptedKeyPrimitives[1]
            };

            var keySequence = new DerSequence(derPrimitives);

            return(keySequence.GetDerEncoded());
        }
コード例 #24
0
        void AddRIoTExtension(X509V3CertificateGenerator certGen, byte[] fwid, AsymmetricCipherKeyPair devIdKey)
        {
            DerObjectIdentifier extensionTag = new DerObjectIdentifier(Program.DeviceIdOid);
            DerOctetString      fwId         = new DerOctetString(fwid);

            var TaggedDevID = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(devIdKey.Public);

            // {hashAlgId,fwidHash}
            var TaggedFWID = new DerSequence(
                new Asn1Encodable[]
            {
                NistObjectIdentifiers.IdSha256,
                new DerOctetString(fwid)
            });

            // {1, devId, fwId}
            var EncodedRIoTIdentity = new DerSequence(
                new Asn1Encodable[]
            {
                new DerInteger(1),      // version number
                TaggedDevID,
                TaggedFWID
            });

            // {riotOid, encodedIdentity}
            var TaggedEncodedRIoTID = new DerSequence(
                new Asn1Encodable[]
            {
                new DerObjectIdentifier(Program.DeviceIdOid),
                EncodedRIoTIdentity
            });


            byte[] ttt = TaggedEncodedRIoTID.GetDerEncoded();
            Debug.WriteLine(Helpers.Hexify(ttt));

            Debug.WriteLine(Asn1Dump.DumpAsString(TaggedEncodedRIoTID));

            certGen.AddExtension(
                X509Extensions.SubjectAlternativeName.Id,
                true,
                new GeneralNames(
                    new GeneralName(GeneralName.OtherName, TaggedEncodedRIoTID)));
        }
コード例 #25
0
        public static ECPublicKeyParameters GetPublicKey(byte[] publicKey)
        {
            Asn1Object keyTypeParameters = new DerSequence(new DerObjectIdentifier(@"1.2.840.10045.2.1"), new DerObjectIdentifier(@"1.2.840.10045.3.1.7"));
            Asn1Object derEncodedKey     = new DerBitString(publicKey);

            Asn1Object derSequence = new DerSequence(keyTypeParameters, derEncodedKey);

            var base64EncodedDerSequence = Convert.ToBase64String(derSequence.GetDerEncoded());
            var pemKey = "-----BEGIN PUBLIC KEY-----\n";

            pemKey += base64EncodedDerSequence;
            pemKey += "\n-----END PUBLIC KEY-----";

            StringReader reader    = new StringReader(pemKey);
            PemReader    pemReader = new PemReader(reader);
            var          keyPair   = pemReader.ReadObject();

            return((ECPublicKeyParameters)keyPair);
        }
コード例 #26
0
        public static ECPrivateKeyParameters GetPrivateKey(byte[] privateKey)
        {
            Asn1Object version           = new DerInteger(1);
            Asn1Object derEncodedKey     = new DerOctetString(privateKey);
            Asn1Object keyTypeParameters = new DerTaggedObject(0, new DerObjectIdentifier(@"1.2.840.10045.3.1.7"));

            Asn1Object derSequence = new DerSequence(version, derEncodedKey, keyTypeParameters);

            var base64EncodedDerSequence = Convert.ToBase64String(derSequence.GetDerEncoded());
            var pemKey = "-----BEGIN EC PRIVATE KEY-----\n";

            pemKey += base64EncodedDerSequence;
            pemKey += "\n-----END EC PRIVATE KEY----";

            var reader    = new StringReader(pemKey);
            var pemReader = new PemReader(reader);
            var keyPair   = (AsymmetricCipherKeyPair)pemReader.ReadObject();

            return((ECPrivateKeyParameters)keyPair.Private);
        }
コード例 #27
0
        /// <summary>
        /// If a device presents a "bare" certificate rather than a full certificate chain, we have to
        /// peform some steps that would normall be performed by the X509 chain builder.  Specifically,
        /// the RIoT extension (above) encodes the DeviceID public key, but we have to check that this
        /// Alias Cert was actually signed by the corresponding DeviceID private key.  To do this we
        /// parse the Alias Cert to get:
        ///     The "to be signed" region (byte array)
        ///     The OID of the signature scheme
        ///     The signature block
        ///
        /// The caller of this function can then check that the ALias Cert was indeed signed by the
        /// device it claims to be from.
        /// </summary>
        /// <param name="aliasCert"></param>
        /// <returns></returns>
        static internal DecomposedCert Decompose(X509Certificate2 aliasCert)
        {
            var rawData = aliasCert.GetRawCertData();

            try
            {
                DerSequence seq       = (DerSequence)DerSequence.FromByteArray(rawData);
                DerSequence tbs       = (DerSequence)seq[0];
                DerSequence sigAlg    = (DerSequence)seq[1];
                var         sigAlgOid = (DerObjectIdentifier)sigAlg[0];

                DerBitString sigData     = (DerBitString)seq[2];
                DerSequence  sigSequence = (DerSequence)DerSequence.FromByteArray(sigData.GetOctets());
                var          sig1        = (DerInteger)sigSequence[0];
                var          sig2        = (DerInteger)sigSequence[0];

                var sig1Bytes = sig1.Value.ToByteArrayUnsigned();
                var sig2Bytes = sig1.Value.ToByteArrayUnsigned();

                Debug.Assert(sig1Bytes.Length == 32 && sig1Bytes.Length == 32);

                byte[] SignatureX = new byte[64];
                Array.Copy(sig1Bytes, 0, SignatureX, 0, 32);
                Array.Copy(sig2Bytes, 0, SignatureX, 32, 32);

                Debug.WriteLine("");

                DecomposedCert bits = new DecomposedCert
                {
                    Tbs       = tbs.GetDerEncoded(),
                    OID       = sigAlgOid.Id,
                    Signature = SignatureX
                };
                return(bits);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());
                return(null);
            }
        }
コード例 #28
0
        public static byte[] EncodeEncryptionParamSet(string encryptionParamSet)
        {
            if (encryptionParamSet == null)
            {
                throw ExceptionUtility.ArgumentNull("encryptionParamSet");
            }

            byte[] data;

            try
            {
                var s = new DerSequence(new DerObjectIdentifier(encryptionParamSet));
                data = s.GetDerEncoded();
            }
            catch (Exception exception)
            {
                throw ExceptionUtility.CryptographicException(exception, Resources.Asn1EncodeError, "Gost2814789BlobParametersEncode");
            }

            return(data);
        }
コード例 #29
0
        private static void PrintPrivateKey(BigInteger pkey, DerObjectIdentifier algId)
        {
            var ecpkey  = new ECPrivateKeyParameters("ECGOST3410", pkey, algId);
            var pkeyEnc = new DerSequence(
                new DerInteger(0),
                new DerSequence(
                    CryptoProObjectIdentifiers.GostR3410x2001,
                    new DerSequence(
                        ecpkey.PublicKeyParamSet,
                        CryptoProObjectIdentifiers.GostR3411x94CryptoProParamSet
                        )
                    ),
                new DerOctetString(new DerInteger(ecpkey.D))
                );

            var pemObject = new PemObject("PRIVATE KEY", pkeyEnc.GetDerEncoded());

            using (var sw = new StreamWriter(Console.OpenStandardOutput())) {
                var writer = new PemWriter(sw);
                writer.WriteObject(pemObject);
            }
        }
コード例 #30
0
        private static void PrintPrivateKey(BigInteger pkey, KeyParameters keyParams)
        {
            var gostParams = Gost3410PublicKeyAlgParameters.GetInstance(keyParams.Algorithm.Parameters);

            var pkeyEnc = new DerSequence(
                new DerInteger(0),
                new DerSequence(
                    keyParams.Algorithm.Algorithm,
                    new DerSequence(
                        gostParams.PublicKeyParamSet,
                        gostParams.DigestParamSet
                        )
                    ),
                new DerOctetString(new DerInteger(pkey))
                );

            var pemObject = new PemObject("PRIVATE KEY", pkeyEnc.GetDerEncoded());

            using (var sw = new StreamWriter(Console.OpenStandardOutput())) {
                var writer = new PemWriter(sw);
                writer.WriteObject(pemObject);
            }
        }