Esempio n. 1
0
 public TomP2POutbound(bool preferDirect, ISignatureFactory signatureFactory, CompByteBufAllocator alloc)
 {
     _preferDirect = preferDirect;
     _signatureFactory = signatureFactory;
     _encoder = new Encoder(signatureFactory);
     _alloc = alloc;
     //Logger.Info("Instantiated with object identity: {0}.", RuntimeHelpers.GetHashCode(this));
 }
 internal SignerInfoGenerator(SignerIdentifier sigId, ISignatureFactory contentSigner, CmsAttributeTableGenerator signedGen, CmsAttributeTableGenerator unsignedGen)
 {
     this.sigId = sigId;
     this.contentSigner = contentSigner;
     this.signedGen = signedGen;
     this.unsignedGen = unsignedGen;
     this.isDirectSignature = false;
 }
 internal SignerInfoGenerator(SignerIdentifier sigId, ISignatureFactory signerFactory, bool isDirectSignature)
 {
     this.sigId = sigId;
     this.contentSigner = signerFactory;
     this.isDirectSignature = isDirectSignature;
     if (this.isDirectSignature)
     {
         this.signedGen = null;
         this.unsignedGen = null;
     }
     else
     {
         this.signedGen = new DefaultSignedAttributeTableGenerator();
         this.unsignedGen = null;
     }
 }
 internal SignerInf(
     CmsSignedGenerator outer,
     ISignatureFactory sigCalc,
     SignerIdentifier signerIdentifier,
     CmsAttributeTableGenerator sAttr,
     CmsAttributeTableGenerator unsAttr,
     Asn1.Cms.AttributeTable baseSignedTable)
 {
     this.outer = outer;
     this.sigCalc = sigCalc;
     this.signerIdentifier = signerIdentifier;
     this.digestOID = new DefaultDigestAlgorithmIdentifierFinder().find((AlgorithmIdentifier)sigCalc.AlgorithmDetails).Algorithm.Id;
     this.encOID = ((AlgorithmIdentifier)sigCalc.AlgorithmDetails).Algorithm.Id;
     this.sAttr = sAttr;
     this.unsAttr = unsAttr;
     this.baseSignedTable = baseSignedTable;
 }
Esempio n. 5
0
 public Task<AVIMClient> CreateClient(string clientId, ISignatureFactory signatureFactory = null, string tag = null)
 {
     CurrentConfiguration = new Configuration()
     {
         ApplicationId = CurrentConfiguration.ApplicationId,
         ApplicationKey = CurrentConfiguration.ApplicationKey,
         SignatureFactory = signatureFactory
     };
     var client = new AVIMClient(clientId, tag)
     {
         SignatureFactory = signatureFactory
     };
     return client.ConnectAsync().ContinueWith(t =>
     {
         return Task.FromResult(client);
     }).Unwrap();
     //return Task.FromResult(new AVIMClient(clientId, tag)
     //{
     //    SignatureFactory = signatureFactory
     //});
 }
			internal SignerInf(
                CmsSignedGenerator			outer,
	            AsymmetricKeyParameter		key,
	            SignerIdentifier			signerIdentifier,
	            string						digestOID,
	            string						encOID,
	            CmsAttributeTableGenerator	sAttr,
	            CmsAttributeTableGenerator	unsAttr,
	            Asn1.Cms.AttributeTable		baseSignedTable)
	        {
                string digestName = Helper.GetDigestAlgName(digestOID);

                string signatureName = digestName + "with" + Helper.GetEncryptionAlgName(encOID);

                this.outer = outer;
                this.sigCalc = new Asn1SignatureFactory(signatureName, key);
                this.signerIdentifier = signerIdentifier;
                this.digestOID = digestOID;
                this.encOID = encOID;
	            this.sAttr = sAttr;
	            this.unsAttr = unsAttr;
	            this.baseSignedTable = baseSignedTable;
            }
 internal SignerInfoGenerator(SignerIdentifier sigId, ISignatureFactory <AlgorithmIdentifier> signerFactory, IDigestFactoryProvider <AlgorithmIdentifier> digesterProvider, ISignatureEncryptionAlgorithmFinder sigEncAlgFinder) : this(sigId, signerFactory, digesterProvider, sigEncAlgFinder, false)
 {
 }
        /// <summary>
        /// Create the RSA certificate as Pfx byte array with a private key.
        /// </summary>
        /// <returns>
        /// Returns the Pfx with certificate and private key.
        /// </returns>
        private byte[] CreatePfxForRSA(string passcode, ISignatureFactory signatureFactory = null)
        {
            // Cases locked out by API flow
            Debug.Assert(m_rsaPublicKey == null, "A public key is not supported for the certificate.");

            if (signatureFactory != null && IssuerCAKeyCert == null)
            {
                throw new NotSupportedException("Need an issuer certificate for a signature generator.");
            }

            if (IssuerCAKeyCert != null &&
                (!IssuerCAKeyCert.HasPrivateKey && signatureFactory == null))
            {
                throw new NotSupportedException("Need an issuer certificate with a private key or a signature generator.");
            }

            using (var cfrg = new CertificateFactoryRandomGenerator())
            {
                // cert generators
                SecureRandom random = new SecureRandom(cfrg);

                CreateDefaults(cfrg);

                X509V3CertificateGenerator cg = new X509V3CertificateGenerator();
                CreateMandatoryFields(cg);

                // create Private/Public Keypair
                AsymmetricKeyParameter subjectPublicKey  = null;
                AsymmetricKeyParameter subjectPrivateKey = null;
                using (var rsa = new RSACryptoServiceProvider(m_keySize == 0 ? X509Defaults.RSAKeySize : m_keySize))
                {
                    subjectPublicKey  = X509Utils.GetPublicKeyParameter(rsa);
                    subjectPrivateKey = X509Utils.GetPrivateKeyParameter(rsa);
                }

                cg.SetPublicKey(subjectPublicKey);
                CreateExtensions(cg, subjectPublicKey);

                // sign certificate
                if (signatureFactory == null)
                {
                    AsymmetricKeyParameter signingKey;
                    if (IssuerCAKeyCert != null)
                    {
                        // signed by issuer
                        signingKey = X509Utils.GetPrivateKeyParameter(IssuerCAKeyCert);
                    }
                    else
                    {
                        // self signed
                        signingKey = subjectPrivateKey;
                    }
                    signatureFactory = new Asn1SignatureFactory(
                        X509Utils.GetRSAHashAlgorithm(HashAlgorithmName), signingKey, random);
                }
                Org.BouncyCastle.X509.X509Certificate x509 = cg.Generate(signatureFactory);

                // note: this Pfx has a private key!
                return(X509Utils.CreatePfxWithPrivateKey(x509, null, subjectPrivateKey, passcode, random));
            }
        }
 /// <summary>
 /// Base constructor.
 /// </summary>
 /// <param name="baseFactory">The base factory to be used in the signing operation.</param>
 public PkixSignatureFactory(ISignatureFactory <IParameters <Algorithm> > baseFactory)
 {
     this.algID       = Utils.GetSigAlgID(baseFactory.AlgorithmDetails);
     this.baseFactory = baseFactory;
 }
Esempio n. 10
0
        /// <summary>
        /// Generate a new X509Crl using the passed in SignatureCalculator.
        /// </summary>
		/// <param name="signatureCalculatorFactory">A signature calculator factory with the necessary algorithm details.</param>
        /// <returns>An X509Crl.</returns>
        public X509Crl Generate(ISignatureFactory signatureCalculatorFactory)
        {
            tbsGen.SetSignature((AlgorithmIdentifier)signatureCalculatorFactory.AlgorithmDetails);

            TbsCertificateList tbsCertList = GenerateCertList();

            IStreamCalculator streamCalculator = signatureCalculatorFactory.CreateCalculator();

            byte[] encoded = tbsCertList.GetDerEncoded();

            streamCalculator.Stream.Write(encoded, 0, encoded.Length);

            Platform.Dispose(streamCalculator.Stream);

            return GenerateJcaObject(tbsCertList, (AlgorithmIdentifier)signatureCalculatorFactory.AlgorithmDetails, ((IBlockResult)streamCalculator.GetResult()).Collect());
        }
 public SignatureFactoryTest()
 {
     signatureFactory = new SignatureFactory();
 }
Esempio n. 12
0
 internal SignerInfoGenerator(SignerIdentifier sigId, ISignatureFactory signerFactory) : this(sigId, signerFactory, false)
 {
 }
Esempio n. 13
0
 public void EncodeDone(AlternativeCompositeByteBuf buffer, ISignatureFactory signatureFactory)
 {
     EncodeDone(buffer, signatureFactory, null);
 }
Esempio n. 14
0
 public bool Verify(IPublicKey publicKey, ISignatureFactory signatureFactory)
 {
     return(signatureFactory.Verify(publicKey, _buffer.ToByteBuf(), Signature));
 }
Esempio n. 15
0
 public Data ProtectEntryNow(KeyPair keyPair, ISignatureFactory signatureFactory)
 {
     return(SignNow(keyPair, signatureFactory, true));
 }
Esempio n. 16
0
 public Data SignNow(IPrivateKey privateKey, ISignatureFactory signatureFactory)
 {
     return(SignNow(privateKey, signatureFactory, false));
 }
Esempio n. 17
0
 public bool Verify(ISignatureFactory signatureFactory)
 {
     return(Verify(PublicKey, signatureFactory));
 }
Esempio n. 18
0
 public Data SignNow(KeyPair keyPair, ISignatureFactory signatureFactory)
 {
     return(SignNow(keyPair, signatureFactory, false));
 }
Esempio n. 19
0
 public bool DecodeDone(AlternativeCompositeByteBuf buffer, IPublicKey publicKey, ISignatureFactory signatureFactory)
 {
     if (IsSigned)
     {
         if (publicKey == PeerBuilder.EmptyPublicKey)
         {
             PublicKey = publicKey;
         }
         return(DecodeDone(buffer, signatureFactory));
     }
     return(true);
 }
Esempio n. 20
0
        public static Data DeocdeHeader(AlternativeCompositeByteBuf buffer, ISignatureFactory signatureFactory)
        {
            // 2 is the smallest packet size, we could start if we know 1 byte to
            // decode the header, but we always need a second byte. Thus, we are waiting for at least 2 bytes.
            if (buffer.ReadableBytes < 2 * Utils.Utils.ByteByteSize)
            {
                return(null);
            }
            int      header = buffer.GetUByte(buffer.ReaderIndex);
            DataType type   = Type(header);

            // length
            int length;
            int indexLength = Utils.Utils.ByteByteSize;
            int indexTtl;

            switch (type)
            {
            case DataType.Small:
                length   = buffer.GetUByte(buffer.ReaderIndex + indexLength);
                indexTtl = indexLength + Utils.Utils.ByteByteSize;
                break;

            case DataType.Large:
                indexTtl = indexLength + Utils.Utils.IntegerByteSize;
                if (buffer.ReadableBytes < indexTtl)
                {
                    return(null);
                }
                length = buffer.GetInt(buffer.ReaderIndex + indexLength);
                break;

            default:
                throw new ArgumentException("Unknown DataType.");
            }

            // TTL
            int ttl;
            int indexBasedOnNr;

            if (CheckHasTtl(header))
            {
                indexBasedOnNr = indexTtl + Utils.Utils.IntegerByteSize;
                if (buffer.ReadableBytes < indexBasedOnNr)
                {
                    return(null);
                }
                ttl = buffer.GetInt(buffer.ReaderIndex + indexTtl);
            }
            else
            {
                indexBasedOnNr = indexTtl;
                ttl            = -1;
            }

            // nr basedOn + basedOn
            int numBasedOn;
            int indexPublicKeySize;
            int indexBasedOn;
            var basedOn = new List <Number160>();

            if (CheckHasBasedOn(header))
            {
                // get nr of basedOn keys
                indexBasedOn = indexBasedOnNr + Utils.Utils.ByteByteSize;
                if (buffer.ReadableBytes < indexBasedOn)
                {
                    return(null);
                }
                numBasedOn         = buffer.GetUByte(buffer.ReaderIndex + indexBasedOn) + 1;
                indexPublicKeySize = indexBasedOn + (numBasedOn * Number160.ByteArraySize);
                if (buffer.ReadableBytes < indexPublicKeySize)
                {
                    return(null);
                }

                // get basedOn
                int index = buffer.ReaderIndex + indexBasedOnNr + Utils.Utils.ByteByteSize;
                var me    = new sbyte[Number160.ByteArraySize];
                for (int i = 0; i < numBasedOn; i++)
                {
                    buffer.GetBytes(index, me);
                    index += Number160.ByteArraySize;
                    basedOn.Add(new Number160(me));
                }
            }
            else
            {
                indexPublicKeySize = indexBasedOnNr;
                numBasedOn         = 0;
            }

            // public key + size
            int        publicKeySize;
            int        indexPublicKey;
            int        indexEnd;
            IPublicKey publicKey;

            if (CheckHasPublicKey(header))
            {
                // get public key size
                indexPublicKey = indexPublicKeySize + Utils.Utils.ShortByteSize;
                if (buffer.ReadableBytes < indexPublicKey)
                {
                    return(null);
                }
                publicKeySize = buffer.GetUShort(buffer.ReaderIndex + indexPublicKeySize);
                indexEnd      = indexPublicKey + publicKeySize;
                if (buffer.ReadableBytes < indexEnd)
                {
                    return(null);
                }

                // get public key
                buffer.SkipBytes(indexPublicKeySize);
                publicKey = signatureFactory.DecodePublicKey(buffer);
            }
            else
            {
                publicKeySize  = 0;
                indexPublicKey = indexPublicKeySize;
                buffer.SkipBytes(indexPublicKey);
                publicKey = null;
            }

            // now, we have read the header and the length
            var data = new Data(header, length);

            data.TtlSeconds = ttl;
            data.BasedOnSet = basedOn;
            data.PublicKey  = publicKey;
            return(data);
        }
        private BasicOcspResp GenerateResponse(ISignatureFactory signatureCalculator, X509Certificate[] chain, global::System.DateTime producedAt)
        {
            //IL_016c: Expected O, but got Unknown
            AlgorithmIdentifier algorithmIdentifier = (AlgorithmIdentifier)signatureCalculator.AlgorithmDetails;
            DerObjectIdentifier algorithm           = algorithmIdentifier.Algorithm;
            Asn1EncodableVector asn1EncodableVector = new Asn1EncodableVector();

            global::System.Collections.IEnumerator enumerator = ((global::System.Collections.IEnumerable)list).GetEnumerator();
            try
            {
                while (enumerator.MoveNext())
                {
                    ResponseObject responseObject = (ResponseObject)enumerator.get_Current();
                    try
                    {
                        asn1EncodableVector.Add(responseObject.ToResponse());
                    }
                    catch (global::System.Exception e)
                    {
                        throw new OcspException("exception creating Request", e);
                    }
                }
            }
            finally
            {
                global::System.IDisposable disposable = enumerator as global::System.IDisposable;
                if (disposable != null)
                {
                    disposable.Dispose();
                }
            }
            ResponseData responseData = new ResponseData(responderID.ToAsn1Object(), new DerGeneralizedTime(producedAt), new DerSequence(asn1EncodableVector), responseExtensions);
            DerBitString derBitString = null;

            try
            {
                IStreamCalculator streamCalculator = signatureCalculator.CreateCalculator();
                byte[]            derEncoded       = responseData.GetDerEncoded();
                streamCalculator.Stream.Write(derEncoded, 0, derEncoded.Length);
                Platform.Dispose(streamCalculator.Stream);
                derBitString = new DerBitString(((IBlockResult)streamCalculator.GetResult()).Collect());
            }
            catch (global::System.Exception ex)
            {
                throw new OcspException(string.Concat((object)"exception processing TBSRequest: ", (object)ex), ex);
            }
            AlgorithmIdentifier sigAlgID = OcspUtilities.GetSigAlgID(algorithm);
            DerSequence         certs    = null;

            if (chain != null && chain.Length > 0)
            {
                Asn1EncodableVector asn1EncodableVector2 = new Asn1EncodableVector();
                try
                {
                    for (int i = 0; i != chain.Length; i++)
                    {
                        asn1EncodableVector2.Add(X509CertificateStructure.GetInstance(Asn1Object.FromByteArray(chain[i].GetEncoded())));
                    }
                }
                catch (IOException val)
                {
                    IOException e2 = val;
                    throw new OcspException("error processing certs", (global::System.Exception)(object) e2);
                }
                catch (CertificateEncodingException e3)
                {
                    throw new OcspException("error encoding certs", e3);
                }
                certs = new DerSequence(asn1EncodableVector2);
            }
            return(new BasicOcspResp(new BasicOcspResponse(responseData, sigAlgID, derBitString, certs)));
        }
Esempio n. 22
0
 public Data ProtectEntryNow(IPrivateKey privateKey, ISignatureFactory signatureFactory)
 {
     return(SignNow(privateKey, signatureFactory, true));
 }
Esempio n. 23
0
        private BasicOcspResp GenerateResponse(
            ISignatureFactory signatureCalculator,
            X509Certificate[]               chain,
            DateTime producedAt)
        {
            AlgorithmIdentifier signingAlgID     = (AlgorithmIdentifier)signatureCalculator.AlgorithmDetails;
            DerObjectIdentifier signingAlgorithm = signingAlgID.Algorithm;

            Asn1EncodableVector responses = new Asn1EncodableVector();

            foreach (ResponseObject respObj in list)
            {
                try
                {
                    responses.Add(respObj.ToResponse());
                }
                catch (Exception e)
                {
                    throw new OcspException("exception creating Request", e);
                }
            }

            ResponseData tbsResp = new ResponseData(responderID.ToAsn1Object(), new DerGeneralizedTime(producedAt), new DerSequence(responses), responseExtensions);
            DerBitString bitSig  = null;

            try
            {
                IStreamCalculator streamCalculator = signatureCalculator.CreateCalculator();

                byte[] encoded = tbsResp.GetDerEncoded();

                streamCalculator.Stream.Write(encoded, 0, encoded.Length);

                Platform.Dispose(streamCalculator.Stream);

                bitSig = new DerBitString(((IBlockResult)streamCalculator.GetResult()).Collect());
            }
            catch (Exception e)
            {
                throw new OcspException("exception processing TBSRequest: " + e, e);
            }

            AlgorithmIdentifier sigAlgId = OcspUtilities.GetSigAlgID(signingAlgorithm);

            DerSequence chainSeq = null;

            if (chain != null && chain.Length > 0)
            {
                Asn1EncodableVector v = new Asn1EncodableVector();
                try
                {
                    for (int i = 0; i != chain.Length; i++)
                    {
                        v.Add(
                            X509CertificateStructure.GetInstance(
                                Asn1Object.FromByteArray(chain[i].GetEncoded())));
                    }
                }
                catch (IOException e)
                {
                    throw new OcspException("error processing certs", e);
                }
                catch (CertificateEncodingException e)
                {
                    throw new OcspException("error encoding certs", e);
                }

                chainSeq = new DerSequence(v);
            }

            return(new BasicOcspResp(new BasicOcspResponse(tbsResp, sigAlgId, bitSig, chainSeq)));
        }
Esempio n. 24
0
 public Data SetSignatureFactory(ISignatureFactory signatureFactory)
 {
     _signatureFactory = signatureFactory;
     return(this);
 }
Esempio n. 25
0
        /// <summary>
        ///   Create a X509 certificate for the specified key.
        /// </summary>
        /// <param name="keyName">
        ///   The key name.
        /// </param>
        /// <param name="cancel"></param>
        /// <returns></returns>
        public async Task <X509Certificate> CreateBCCertificateAsync(
            string keyName,
            CancellationToken cancel = default(CancellationToken))
        {
            // Get the BC key pair for the named key.
            var ekey = await Store.TryGetAsync(keyName, cancel).ConfigureAwait(false);

            if (ekey == null)
            {
                throw new KeyNotFoundException($"The key '{keyName}' does not exist.");
            }
            AsymmetricCipherKeyPair kp = null;

            UseEncryptedKey(ekey, key =>
            {
                kp = this.GetKeyPairFromPrivateKey(key);
            });

            // A signer for the key.
            var ku = new KeyUsage(KeyUsage.DigitalSignature
                                  | KeyUsage.DataEncipherment
                                  | KeyUsage.KeyEncipherment);
            ISignatureFactory signatureFactory = null;

            if (kp.Private is ECPrivateKeyParameters)
            {
                signatureFactory = new Asn1SignatureFactory(
                    X9ObjectIdentifiers.ECDsaWithSha256.ToString(),
                    kp.Private);
            }
            else if (kp.Private is RsaPrivateCrtKeyParameters)
            {
                signatureFactory = new Asn1SignatureFactory(
                    PkcsObjectIdentifiers.Sha256WithRsaEncryption.ToString(),
                    kp.Private);
            }
            else if (kp.Private is Ed25519PrivateKeyParameters)
            {
                signatureFactory = new Asn1SignatureFactory(
                    EdECObjectIdentifiers.id_Ed25519.Id.ToString(),
                    kp.Private);
                ku = new KeyUsage(KeyUsage.DigitalSignature);
            }
            if (signatureFactory == null)
            {
                throw new NotSupportedException($"The key type {kp.Private.GetType().Name} is not supported.");
            }

            // Build the certificate.
            var dn  = new X509Name($"CN={ekey.Id}, OU=keystore, O=ipfs");
            var ski = new SubjectKeyIdentifier(Base58.Decode(ekey.Id));
            // Not a certificate authority.
            // TODO: perhaps the "self" key is a CA and all other keys issued by it.
            var bc = new BasicConstraints(false);

            var certGenerator = new X509V3CertificateGenerator();

            certGenerator.SetIssuerDN(dn);
            certGenerator.SetSubjectDN(dn);
            certGenerator.SetSerialNumber(BigInteger.ValueOf(1));
            certGenerator.SetNotAfter(DateTime.UtcNow.AddYears(10));
            certGenerator.SetNotBefore(DateTime.UtcNow);
            certGenerator.SetPublicKey(kp.Public);
            certGenerator.AddExtension(X509Extensions.SubjectKeyIdentifier, false, ski);
            certGenerator.AddExtension(X509Extensions.BasicConstraints, true, bc);
            certGenerator.AddExtension(X509Extensions.KeyUsage, false, ku);

            return(certGenerator.Generate(signatureFactory));
        }
        /// <summary>
        /// Instantiate a Pkcs10CertificationRequest object with the necessary credentials.
        /// </summary>
        ///<param name="signatureCalculatorFactory">The factory for signature calculators to sign the PKCS#10 request with.</param>
        /// <param name="subject">X509Name of subject eg OU="My unit." O="My Organisatioin" C="au" </param>
        /// <param name="publicKey">Public Key to be included in cert reqest.</param>
        /// <param name="attributes">ASN1Set of Attributes.</param>
        /// <param name="signingKey">Matching Private key for nominated (above) public key to be used to sign the request.</param>
        public Pkcs10CertificationRequest(
            ISignatureFactory signatureCalculatorFactory,
            X509Name subject,
            AsymmetricKeyParameter publicKey,
            Asn1Set attributes,
            AsymmetricKeyParameter signingKey)
        {
            if (signatureCalculatorFactory == null)
                throw new ArgumentNullException("signatureCalculator");
            if (subject == null)
                throw new ArgumentNullException("subject");
            if (publicKey == null)
                throw new ArgumentNullException("publicKey");
            if (publicKey.IsPrivate)
                throw new ArgumentException("expected public key", "publicKey");
            if (!signingKey.IsPrivate)
                throw new ArgumentException("key for signing must be private", "signingKey");

            init(signatureCalculatorFactory, subject, publicKey, attributes, signingKey);
        }
 internal SigWithDigest(ISignatureFactory <IParameters <Algorithm> > sigFact, IDigestFactory <IParameters <Algorithm> > digFact)
 {
     this.sigCalc     = sigFact.CreateCalculator();
     this.digCalc     = digFact.CreateCalculator();
     this.jointStream = new TeeOutputStream(sigCalc.Stream, digCalc.Stream);
 }
        private void init(
            ISignatureFactory signatureCalculator, 
            X509Name subject,
            AsymmetricKeyParameter publicKey,
            Asn1Set attributes,
            AsymmetricKeyParameter signingKey)
        {
            this.sigAlgId = (AlgorithmIdentifier)signatureCalculator.AlgorithmDetails;

            SubjectPublicKeyInfo pubInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);

            this.reqInfo = new CertificationRequestInfo(subject, pubInfo, attributes);

            IStreamCalculator streamCalculator = signatureCalculator.CreateCalculator();

            byte[] reqInfoData = reqInfo.GetDerEncoded();

            streamCalculator.Stream.Write(reqInfoData, 0, reqInfoData.Length);

            Platform.Dispose(streamCalculator.Stream);

            // Generate Signature.
            sigBits = new DerBitString(((IBlockResult)streamCalculator.GetResult()).Collect());
        }
Esempio n. 29
0
 public TomP2PSinglePacketUdp(ISignatureFactory signatureFactory)
 {
     _signatureFactory = signatureFactory;
 }
Esempio n. 30
0
 public TomP2POutbound(bool preferDirect, ISignatureFactory signatureFactory)
     : this(preferDirect, signatureFactory, new CompByteBufAllocator())
 { }
Esempio n. 31
0
        private static X509Certificate SignCertificateFromRequest(Pkcs10CertificationRequest request, ISignatureFactory signer)
        {
            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

            DateTime now = DateTime.Now;

            certGen.SetIssuerDN(request.GetCertificationRequestInfo().Subject);
            certGen.SetSubjectDN(request.GetCertificationRequestInfo().Subject);
            certGen.SetNotAfter(now.AddDays(7));
            certGen.SetNotBefore(now.AddMinutes(-10));
            certGen.SetSerialNumber(new Org.BouncyCastle.Math.BigInteger(80, new Random()));
            certGen.SetPublicKey(request.GetPublicKey());

            return(certGen.Generate(signer));
        }
Esempio n. 32
0
        public Blockchain(Wallet miningWallet, IWalletManager walletManager, IHashFactory transactionHashFactory, ISignatureFactory signatureFactory, IMiningFactory miningFactory, IBlockStorage storage)
        {
            SignatureFactory = signatureFactory;
            Verifier         = signatureFactory.GetSignatureVerifier();

            MiningFactory = miningFactory;

            TransactionHashFactory = transactionHashFactory;
            Digest = TransactionHashFactory.GetDigest();

            MiningWallet  = miningWallet;
            WalletManager = walletManager;

            pendingTransactions = new LinkedList <Transaction>();
            storedChain         = storage;

            foreach (Block block in storedChain)
            {
                WalletManager.AcceptTransactions(block.Transactions);
            }
        }
Esempio n. 33
0
 public Decoder(ISignatureFactory signatureFactory)
 {
     _signatureFactory = signatureFactory;
     Logger.Info("Instantiated with object identity: {0}.", RuntimeHelpers.GetHashCode(this));
 }
		private BasicOcspResp GenerateResponse(
			ISignatureFactory    signatureCalculator,
			X509Certificate[]		chain,
			DateTime				producedAt)
		{
            AlgorithmIdentifier signingAlgID = (AlgorithmIdentifier)signatureCalculator.AlgorithmDetails;
            DerObjectIdentifier signingAlgorithm = signingAlgID.Algorithm;

			Asn1EncodableVector responses = new Asn1EncodableVector();

			foreach (ResponseObject respObj in list)
			{
				try
				{
					responses.Add(respObj.ToResponse());
				}
				catch (Exception e)
				{
					throw new OcspException("exception creating Request", e);
				}
			}

			ResponseData tbsResp = new ResponseData(responderID.ToAsn1Object(), new DerGeneralizedTime(producedAt), new DerSequence(responses), responseExtensions);
			DerBitString bitSig = null;

			try
			{
                IStreamCalculator streamCalculator = signatureCalculator.CreateCalculator();

				byte[] encoded = tbsResp.GetDerEncoded();

                streamCalculator.Stream.Write(encoded, 0, encoded.Length);

                Platform.Dispose(streamCalculator.Stream);

                bitSig = new DerBitString(((IBlockResult)streamCalculator.GetResult()).Collect());
			}
			catch (Exception e)
			{
				throw new OcspException("exception processing TBSRequest: " + e, e);
			}

			AlgorithmIdentifier sigAlgId = OcspUtilities.GetSigAlgID(signingAlgorithm);

			DerSequence chainSeq = null;
			if (chain != null && chain.Length > 0)
			{
				Asn1EncodableVector v = new Asn1EncodableVector();
				try
				{
					for (int i = 0; i != chain.Length; i++)
					{
						v.Add(
							X509CertificateStructure.GetInstance(
								Asn1Object.FromByteArray(chain[i].GetEncoded())));
					}
				}
				catch (IOException e)
				{
					throw new OcspException("error processing certs", e);
				}
				catch (CertificateEncodingException e)
				{
					throw new OcspException("error encoding certs", e);
				}

				chainSeq = new DerSequence(v);
			}

			return new BasicOcspResp(new BasicOcspResponse(tbsResp, sigAlgId, bitSig, chainSeq));
		}
 public PkixSignatureFactory(AlgorithmIdentifier algorithmIdentifier, ISignatureFactory <IParameters <Algorithm> > baseFactory)
 {
     this.algID       = algorithmIdentifier;
     this.baseFactory = baseFactory;
 }
        /// <summary>
        /// Generate the signed response using the passed in signature calculator.
        /// </summary>
        /// <param name="signatureCalculatorFactory">Implementation of signing calculator factory.</param>
        /// <param name="chain">The certificate chain associated with the response signer.</param>
        /// <param name="producedAt">"produced at" date.</param>
        /// <returns></returns>
        public BasicOcspResp Generate(
            ISignatureFactory signatureCalculatorFactory,
            X509Certificate[] chain,
            DateTime producedAt)
        {
            if (signatureCalculatorFactory == null)
            {
                throw new ArgumentException("no signature calculator specified");
            }

            return GenerateResponse(signatureCalculatorFactory, chain, producedAt);
        }
Esempio n. 37
0
        public static X509Certificate GenerateCertificate(SecureRandom random,
                                                          string subjectName,
                                                          AsymmetricCipherKeyPair subjectKeyPair,
                                                          BigInteger subjectSerialNumber,
                                                          string[] subjectAlternativeNames,
                                                          string issuerName,
                                                          AsymmetricCipherKeyPair issuerKeyPair,
                                                          BigInteger issuerSerialNumber,
                                                          bool isCertificateAuthority,
                                                          KeyPurposeID[] usages)
        {
            var certificateGenerator = new X509V3CertificateGenerator();

            certificateGenerator.SetSerialNumber(subjectSerialNumber);

            // Set the signature algorithm. This is used to generate the thumbprint which is then signed
            // with the issuer's private key. We'll use SHA-256, which is (currently) considered fairly strong.
            //const string signatureAlgorithm = "SHA256WithRSA";
            //certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm);
            // set the hash algorithm
            ISignatureFactory signatureFactory = null;

            if (isCertificateAuthority)
            {
                signatureFactory = new Asn1SignatureFactory(PkcsObjectIdentifiers.Sha1WithRsaEncryption.ToString(), subjectKeyPair.Private, random);
            }
            else
            {
                signatureFactory = new Asn1SignatureFactory(PkcsObjectIdentifiers.Sha256WithRsaEncryption.ToString(), subjectKeyPair.Private, random);
            }

            var issuerDN = new X509Name(issuerName);

            certificateGenerator.SetIssuerDN(issuerDN);

            // Note: The subject can be omitted if you specify a subject alternative name (SAN).
            var subjectDN = new X509Name(subjectName);

            certificateGenerator.SetSubjectDN(subjectDN);

            // Our certificate needs valid from/to values.
            var notBefore = DateTime.UtcNow.Date;
            var notAfter  = notBefore.AddYears(20);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            // The subject's public key goes in the certificate.
            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            AddAuthorityKeyIdentifier(certificateGenerator, issuerDN, issuerKeyPair, issuerSerialNumber);
            AddSubjectKeyIdentifier(certificateGenerator, subjectKeyPair);
            AddBasicConstraints(certificateGenerator, isCertificateAuthority);

            if (usages != null && usages.Any())
            {
                AddExtendedKeyUsage(certificateGenerator, usages);
            }

            if (subjectAlternativeNames != null && subjectAlternativeNames.Any())
            {
                AddSubjectAlternativeNames(certificateGenerator, subjectAlternativeNames);
            }

            // The certificate is signed with the issuer's private key.
            var certificate = certificateGenerator.Generate(signatureFactory);//issuerKeyPair.Private, random);

            return(certificate);
        }
Esempio n. 38
0
        /**
         * Build a generator with the passed in subjectKeyIdentifier as the signerIdentifier. If used  you should
         * try to follow the calculation described in RFC 5280 section 4.2.1.2.
         *
         * @param signerFactory  operator factory for generating the final signature in the SignerInfo with.
         * @param subjectKeyIdentifier    key identifier to identify the public key for verifying the signature.
         * @return  a SignerInfoGenerator
         */
        public SignerInfoGenerator Build(ISignatureFactory signerFactory, byte[] subjectKeyIdentifier)
        {
            SignerIdentifier sigId = new SignerIdentifier(new DerOctetString(subjectKeyIdentifier));

            return(CreateGenerator(signerFactory, sigId));
        }
Esempio n. 39
0
 public TomP2PCumulationTcp(ISignatureFactory signatureFactory)
 {
     _signatureFactory = signatureFactory;
     _decoder          = new Decoder(signatureFactory);
 }
 /// <summary>
 /// Sets the factory for the signature.
 /// </summary>
 /// <param name="signatureFactory"></param>
 /// <returns>This class.</returns>
 public ChannelClientConfiguration SetSignatureFactory(ISignatureFactory signatureFactory)
 {
     SignatureFactory = signatureFactory;
     return this;
 }
Esempio n. 41
0
 public Encoder(ISignatureFactory signatureFactory)
 {
     _signatureFactory = signatureFactory;
     Logger.Info("Instantiated with object identity: {0}.", RuntimeHelpers.GetHashCode(this));
 }
Esempio n. 42
0
 public TomP2PCumulationTcp(ISignatureFactory signatureFactory)
 {
     _signatureFactory = signatureFactory;
     _decoder = new Decoder(signatureFactory);
 }
 /// <summary>
 /// 启用 LeanEngine 云函数签名
 /// </summary>
 public void UseLeanEngineSignatureFactory()
 {
     useLeanEngineSignaturFactory = true;
     this.SignatureFactory        = new LeanEngineSignatureFactory();
 }
Esempio n. 44
0
        /// <summary>
        /// Build a generator with the passed in subjectKeyIdentifier as the signerIdentifier. If used  you should
        /// try to follow the calculation described in RFC 5280 section 4.2.1.2.
        /// </summary>
        /// <param name="contentSigner">operator factory for generating the final signature in the SignerInfo with.</param>
        /// <param name="subjectKeyIdentifier">key identifier to identify the public key for verifying the signature.</param>
        /// <returns>a SignerInfoGenerator</returns>
        public SignerInfoGenerator Build(ISignatureFactory <AlgorithmIdentifier> contentSigner, byte[] subjectKeyIdentifier)
        {
            SignerIdentifier sigId = new SignerIdentifier(new DerOctetString(subjectKeyIdentifier));

            return(CreateGenerator(contentSigner, sigId));
        }
        /**
         * Build a generator with the passed in certHolder issuer and serial number as the signerIdentifier.
         *
         * @param contentSigner  operator for generating the final signature in the SignerInfo with.
         * @param certHolder  carrier for the X.509 certificate related to the contentSigner.
         * @return  a SignerInfoGenerator
         * @throws OperatorCreationException   if the generator cannot be built.
         */
        public SignerInfoGenerator Build(ISignatureFactory contentSigner, X509Certificate certificate)
        {
            SignerIdentifier sigId = new SignerIdentifier(new IssuerAndSerialNumber(certificate.IssuerDN, new DerInteger(certificate.SerialNumber)));

            SignerInfoGenerator sigInfoGen = CreateGenerator(contentSigner, sigId);

            sigInfoGen.setAssociatedCertificate(certificate);

            return sigInfoGen;
        }
Esempio n. 46
0
        public void EncodeHeader(AlternativeCompositeByteBuf buffer, ISignatureFactory signatureFactory)
        {
            int header = (int)_type; // TODO check if works

            if (HasPrepareFlag)
            {
                header |= 0x02;
            }
            if (IsFlag1)
            {
                header |= 0x04;
            }
            if (IsFlag2)
            {
                header |= 0x08;
            }
            if (_ttl)
            {
                header |= 0x10;
            }
            if (IsSigned && HasPublicKey && IsProtectedEntry)
            {
                header |= (0x20 | 0x40);
            }
            else if (IsSigned && HasPublicKey)
            {
                header |= 0x40;
            }
            else if (HasPublicKey)
            {
                header |= 0x20;
            }
            if (_basedOnFlag)
            {
                header |= 0x80;
            }
            switch (_type)
            {
            case DataType.Small:
                buffer.WriteByte((sbyte)header);     // TODO remove cast
                buffer.WriteByte((sbyte)Length);
                break;

            case DataType.Large:
                buffer.WriteByte((sbyte)header);     // TODO remove cast
                buffer.WriteInt(Length);
                break;

            default:
                throw new ArgumentException("Unknown DataType.");
            }
            if (_ttl)
            {
                buffer.WriteInt(TtlSeconds);
            }
            if (_basedOnFlag)
            {
                buffer.WriteByte((sbyte)(BasedOnSet.Count() - 1)); // TODO remove cast
                foreach (var basedOn in BasedOnSet)
                {
                    buffer.WriteBytes(basedOn.ToByteArray());
                }
            }
            if (HasPublicKey)
            {
                if (PublicKey == null)
                {
                    buffer.WriteShort(0);
                }
                else
                {
                    signatureFactory.EncodePublicKey(PublicKey, buffer);
                }
            }
        }
		/// <summary>
		/// Generate a new X509Certificate using the passed in SignatureCalculator.
		/// </summary>
		/// <param name="signatureCalculatorFactory">A signature calculator factory with the necessary algorithm details.</param>
		/// <returns>An X509Certificate.</returns>
		public X509Certificate Generate(ISignatureFactory signatureCalculatorFactory)
		{
			tbsGen.SetSignature ((AlgorithmIdentifier)signatureCalculatorFactory.AlgorithmDetails);

            if (!extGenerator.IsEmpty)
            {
                tbsGen.SetExtensions(extGenerator.Generate());
            }

            TbsCertificateStructure tbsCert = tbsGen.GenerateTbsCertificate();

			IStreamCalculator streamCalculator = signatureCalculatorFactory.CreateCalculator();

			byte[] encoded = tbsCert.GetDerEncoded();

			streamCalculator.Stream.Write(encoded, 0, encoded.Length);

            Platform.Dispose(streamCalculator.Stream);

            return GenerateJcaObject(tbsCert, (AlgorithmIdentifier)signatureCalculatorFactory.AlgorithmDetails, ((IBlockResult)streamCalculator.GetResult()).Collect());
		}
        /**
         * Build a generator with the passed in subjectKeyIdentifier as the signerIdentifier. If used  you should
         * try to follow the calculation described in RFC 5280 section 4.2.1.2.
         *
         * @param signerFactory  operator factory for generating the final signature in the SignerInfo with.
         * @param subjectKeyIdentifier    key identifier to identify the public key for verifying the signature.
         * @return  a SignerInfoGenerator
         */
        public SignerInfoGenerator Build(ISignatureFactory signerFactory, byte[] subjectKeyIdentifier)
        {
            SignerIdentifier sigId = new SignerIdentifier(new DerOctetString(subjectKeyIdentifier));

            return CreateGenerator(signerFactory, sigId);
        }
        private SignerInfoGenerator CreateGenerator(ISignatureFactory contentSigner, SignerIdentifier sigId)
        {
            if (directSignature)
            {
                return new SignerInfoGenerator(sigId, contentSigner, true);
            }

            if (signedGen != null || unsignedGen != null)
            {
                if (signedGen == null)
                {
                    signedGen = new DefaultSignedAttributeTableGenerator();
                }

                return new SignerInfoGenerator(sigId, contentSigner, signedGen, unsignedGen);
            }

            return new SignerInfoGenerator(sigId, contentSigner);
        }
        internal SignerInfoGenerator(SignerIdentifier sigId, ISignatureFactory signerFactory): this(sigId, signerFactory, false)
        {

        }
 public TomP2PSinglePacketUdp(ISignatureFactory signatureFactory)
 {
     _signatureFactory = signatureFactory;
 }
        /// <summary>
        /// Generate a new X.509 Attribute Certificate using the passed in SignatureCalculator.
        /// </summary>
        /// <param name="signatureCalculatorFactory">A signature calculator factory with the necessary algorithm details.</param>
        /// <returns>An IX509AttributeCertificate.</returns>
        public IX509AttributeCertificate Generate(ISignatureFactory signatureCalculatorFactory)
        {
            if (!extGenerator.IsEmpty)
			{
				acInfoGen.SetExtensions(extGenerator.Generate());
			}

			AttributeCertificateInfo acInfo = acInfoGen.GenerateAttributeCertificateInfo();

            byte[] encoded = acInfo.GetDerEncoded();

            IStreamCalculator streamCalculator = signatureCalculatorFactory.CreateCalculator();

            streamCalculator.Stream.Write(encoded, 0, encoded.Length);

            Platform.Dispose(streamCalculator.Stream);

            Asn1EncodableVector v = new Asn1EncodableVector();

			v.Add(acInfo, (AlgorithmIdentifier)signatureCalculatorFactory.AlgorithmDetails);

			try
			{
				v.Add(new DerBitString(((IBlockResult)streamCalculator.GetResult()).Collect()));

				return new X509V2AttributeCertificate(AttributeCertificate.GetInstance(new DerSequence(v)));
			}
			catch (Exception e)
			{
				// TODO
//				throw new ExtCertificateEncodingException("constructed invalid certificate", e);
				throw new CertificateEncodingException("constructed invalid certificate", e);
			}
		}