private string GeneratePassword(ushort passwordLength = 12)
        {
            const string randomChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()";
            ushort       MAX_LENGTH  = (ushort)randomChars.Length;

            char[] randomElements = randomChars.ToCharArray();
            byte[] randomBytes    = new byte[4];
            System.Security.Cryptography.RandomNumberGenerator random = System.Security.Cryptography.RandomNumberGenerator.Create();
            random.GetBytes(randomBytes);
            int           randomSeed    = BitConverter.ToInt32(randomBytes, 0);
            Random        realRandom    = new Random(randomSeed);
            StringBuilder finalPassword = new StringBuilder();

            for (short i = 0; i < passwordLength; i++)
            {
                finalPassword.Append(randomElements[realRandom.Next(0, MAX_LENGTH)]);
            }
            return(finalPassword.ToString());
        }
        /// <summary>
        /// Encodes the session key stored in the SessionKey property
        /// and saves the result in the EncodedSessionKey property.
        /// </summary>
        /// <param name="nKeySize">The size of the asymmetrical
        /// key used to encrypt the symmetrical session key.</param>
        /// <remarks>No remarks</remarks>
        public void EncodeSessionKey(int nKeySize)
        {
            byte[] bData = new byte[(nKeySize + 7) / 8];

            if (bSessionKey.Length > bData.Length - 6)
            {
                throw(new System.ArgumentException("Either the keylength is too short, or the session key is too long. either way: it's not possible to encode the sessionway!"));
            }

            uint iChecksum = 0;

            for (int i = 0; i < bSessionKey.Length; i++)
            {
                iChecksum = (iChecksum + (uint)bSessionKey[i]) % 65536;
            }

            int iPos = 0;

            bData[iPos++] = 0;
            bData[iPos++] = 2;

            int nRandomBytes = bData.Length - 6 - bSessionKey.Length;

            System.Security.Cryptography.RandomNumberGenerator rngRandom = System.Security.Cryptography.RandomNumberGenerator.Create();

            byte[] bRandom = new byte[nRandomBytes];
            rngRandom.GetNonZeroBytes(bRandom);

            Array.Copy(bRandom, 0, bData, iPos, bRandom.Length);
            iPos += bRandom.Length;

            bData[iPos++] = 0;
            bData[iPos++] = (byte)saSymmetricAlgorithm;

            Array.Copy(bSessionKey, 0, bData, iPos, bSessionKey.Length);
            iPos += bSessionKey.Length;

            bData[iPos++] = (byte)((iChecksum >> 8) & 0xFF);
            bData[iPos++] = (byte)(iChecksum & 0xFF);

            this.bIsUpdated    = true;
            bEncodedSessionKey = bData;
        }
Esempio n. 3
0
        public char GetRandChar(int lang)
        {
            if (lang == 0)
            {
                return((char)Rand.GetInt32(lenOfDev));
            }

            string alfabet;

            if (lang == 1)
            {
                alfabet = alfabetEn;
            }
            else
            {
                alfabet = alfabetUa;
            }

            return(alfabet[Rand.GetInt32(alfabet.Length)]);
        }
        public static bool _Create_System_String( )
        {
            //Parameters
            System.String rngName = null;

            //ReturnType/Value
            System.Security.Cryptography.RandomNumberGenerator returnVal_Real        = null;
            System.Security.Cryptography.RandomNumberGenerator returnVal_Intercepted = null;

            //Exception
            Exception exception_Real        = null;
            Exception exception_Intercepted = null;

            InterceptionMaintenance.disableInterception( );

            try
            {
                returnValue_Real = System.Security.Cryptography.RandomNumberGenerator.Create(rngName);
            }

            catch (Exception e)
            {
                exception_Real = e;
            }


            InterceptionMaintenance.enableInterception( );

            try
            {
                returnValue_Intercepted = System.Security.Cryptography.RandomNumberGenerator.Create(rngName);
            }

            catch (Exception e)
            {
                exception_Intercepted = e;
            }


            Return((exception_Real.Messsage == exception_Intercepted.Message) && (returnValue_Real == returnValue_Intercepted));
        }
Esempio n. 5
0
 public void FillBuffer()
 {
     if (IsLinux)
     {
         FileStream fs = File.OpenRead("/dev/random");
         for (int i = 0; i < bufferSize; i++)
         {
             buffer[i] = (byte)fs.ReadByte();
         }
         fs.Close();
     }
     else
     {
         if (rng == null)
         {
             rng = System.Security.Cryptography.RandomNumberGenerator.Create();
         }
         rng.GetBytes(buffer);
         rng.Dispose();
     }
     bufferIndex = 0;
 }
Esempio n. 6
0
 internal static BigInteger NextBigInteger(this System.Security.Cryptography.RandomNumberGenerator rng, int sizeInBits)
 {
     if (sizeInBits < 0)
     {
         throw new ArgumentException("sizeInBits must be non-negative");
     }
     if (sizeInBits == 0)
     {
         return(0);
     }
     byte[] b = new byte[sizeInBits / 8 + 1];
     rng.GetBytes(b);
     if (sizeInBits % 8 == 0)
     {
         b[b.Length - 1] = 0;
     }
     else
     {
         b[b.Length - 1] &= (byte)((1 << sizeInBits % 8) - 1);
     }
     return(new BigInteger(b));
 }
        /// <summary>
        /// Creates a new symmetrical session key packet. Format defaults
        /// to new packet format.
        /// </summary>
        public SymSessionKeyPacket()
        {
            bBody     = new byte[0];
            bHeader   = new byte[0];
            pfFormat  = PacketFormats.New;
            ctContent = ContentTypes.SymSessionKey;
            this.bEncryptedSessionKey = new byte[0];

            s2kSpecifier       = new String2KeySpecifier();
            s2kSpecifier.Type  = String2KeySpecifierTypes.IteraterSaltedS2K;
            s2kSpecifier.Count = 96;

            byte[] bSalt = new byte[8];
            System.Security.Cryptography.RandomNumberGenerator rngRand = System.Security.Cryptography.RandomNumberGenerator.Create();
            rngRand.GetBytes(bSalt);

            S2KSpecifier.Salt = 0;
            S2KSpecifier.Salt = ((ulong)bSalt[0] << 56) ^ ((ulong)bSalt[1] << 48) ^
                                ((ulong)bSalt[2] << 40) ^ ((ulong)bSalt[3] << 32) ^
                                ((ulong)bSalt[3] << 24) ^ ((ulong)bSalt[5] << 16) ^
                                ((ulong)bSalt[6] << 8) ^ (ulong)bSalt[7];
            this.bIsUpdated = true;
        }
Esempio n. 8
0
        private JObject CreateAddress()
        {
            var privateKey = new byte[32];

            using (var generator = RandomNumberGenerator.Create())
            {
                generator.GetBytes(privateKey);
            }

            var kp = new KeyPair(privateKey);

            var jaddress = new JObject();

            var address = kp.AsAddress();

            jaddress["wif"]        = kp.Export();
            jaddress["address"]    = address;
            jaddress["privkey"]    = kp.PrivateKey.ToHexString();
            jaddress["pubkey"]     = kp.PublicKey.ToString();
            jaddress["scripthash"] = address.ToScriptHash().ToString();

            return(jaddress);
        }
Esempio n. 9
0
        public static MemoryStream GetRandomMemoryStream(int length)
        {
            MemoryStream memStm = new MemoryStream();

            System.Security.Cryptography.RandomNumberGenerator rndGen =
                System.Security.Cryptography.RandomNumberGenerator.Create();
            byte[] buf   = new byte[BYTE_BUFFER_LENGTH];
            int    count = 0;

            while (count < length)
            {
                int l = length - count;
                if (l > buf.Length)
                {
                    l = buf.Length;
                }
                rndGen.GetBytes(buf);
                memStm.Write(buf, 0, l);
                count += l;
            }
            memStm.Seek(0, SeekOrigin.Begin);
            return(memStm);
        }
Esempio n. 10
0
        private static void BuildFrameHeader(FrameOpcode opcode, int appDataLength, bool masking, out byte[] maskData, out byte[] buffer, out int appDataOffset, bool bareHeader)
        {
            PayloadLengthMode plm;

            if (appDataLength < 126)
            {
                plm = PayloadLengthMode.Short;
            }
            else if (appDataLength <= UInt16.MaxValue)
            {
                plm = PayloadLengthMode.Medium;
            }
            else
            {
                plm = PayloadLengthMode.Long;
            }

            // TODO: implement extensions
            int bufferLength = 2 + (((int)plm) / 8) + (masking ? 4 : 0) + (bareHeader ? 0 : appDataLength);

            buffer    = new byte[bufferLength];
            buffer[0] = (byte)((byte)opcode | FLAG1_FIN);

            switch (plm)
            {
            case PayloadLengthMode.Short:
                buffer[1]     = (byte)appDataLength;
                appDataOffset = 2;
                break;

            case PayloadLengthMode.Medium:
                buffer[1] = 126;
                var shortLength = Util.ReverseArray(BitConverter.GetBytes(checked ((UInt16)appDataLength)));
                Array.Copy(shortLength, 0, buffer, 2, shortLength.Length);
                appDataOffset = 4;
                break;

            case PayloadLengthMode.Long:
                buffer[1] = 127;
                var longLength = Util.ReverseArray(BitConverter.GetBytes(checked ((UInt64)appDataLength)));
                Array.Copy(longLength, 0, buffer, 2, longLength.Length);
                appDataOffset = 10;
                break;

            default:
                throw new InvalidOperationException("Either the string is impossibly large (HI FUTURE! :D) or the selection loop (or the switch) has failed.");
            }

            if (masking)
            {
                maskData = new byte[4];
                if (CSPRNG == null)
                {
                    CSPRNG = System.Security.Cryptography.RandomNumberGenerator.Create();
                }
                CSPRNG.GetBytes(maskData);
                buffer[1] |= FLAG2_MASK;
                Array.Copy(maskData, 0, buffer, appDataOffset, maskData.Length);
                appDataOffset += 4;
            }
            else
            {
                maskData = null;
            }
        }
Esempio n. 11
0
 /// <summary>
 /// Sets the underlying random number generator used by the BigIntegerRandom to
 /// generate random BigIntegers.
 /// </summary>
 /// <remarks>If a Random type generator and a RandomNumberGenerator type generator
 /// are set, the RandomNumberGenerator type will be used.If a random number generator
 /// is not explicitly set, a Random object created with the default seed will be used
 /// by BigIntegerRandom.</remarks>
 /// <param name="rng">The RandomNumberGenerator object that will be used to generate random BigIntegers.</param>
 public void SetRandomNumberGenerator(System.Security.Cryptography.RandomNumberGenerator rng)
 {
     this.rng = rng;
 }
Esempio n. 12
0
 public RandomSwapImpl(System.Security.Cryptography.RandomNumberGenerator rng)
 {
     moRng = rng;
 }
Esempio n. 13
0
        /// <summary>
        /// Генерирует предложение
        /// </summary>
        /// <param name="pattern">Структура предложения</param>
        /// <returns>Предложение</returns>
        public static string Generate(string pattern)
        {
            List <Word> Unterminates = GetUnterminates(pattern.Split(" ".ToArray(), StringSplitOptions.RemoveEmptyEntries));
            bool        solved       = false;
            List <Word> Sentence     = Unterminates;

            while (!solved)
            {
                solved = true;
                List <Word> newSentence = new List <Word>();
                newSentence.Add(Dot);
                for (int i = Sentence.Count - 1; i >= 0; i--)
                {
                    if (Sentence[i].Type == WordType.Unterminate)
                    {
                        solved = false;
                        var subwords = SelectPath(Sentence[i] as UnTerminateWord);
                        for (int k = 0; k < subwords.Count; k++)
                        {
                            if (subwords[k].Type == WordType.Terminate)
                            {
                                ((TerminateWord)subwords[k]).SpellPart = ((UnTerminateWord)Sentence[i]).SpellPart;
                            }
                        }

                        newSentence.InsertRange(0, subwords);
                    }
                    else if (Sentence[i] != Dot)
                    {
                        newSentence.Insert(0, Sentence[i]);
                    }
                }

                if (!solved)
                {
                    Sentence = newSentence;
                }
            }

            var           TSentence = Sentence.Select(word => word as TerminateWord).ToList();
            StringBuilder builder   = new StringBuilder();
            WordTime      time      = (WordTime)Randomize(0, 2);

            for (int i = 0; i < TSentence.Count; i++)
            {
                TerminateWord tword   = TSentence[i];
                string        wordStr = "";
                switch (tword.SentencePart)
                {
                case Terminate.Существительное:
                    wordStr = (tword as Noun).GetNoun();
                    break;

                case Terminate.Глагол:
                {
                    var        verb = (tword as Verb);
                    var        noun = TSentence.First(word => word.SentencePart == Terminate.Существительное);
                    WordGender gen  = (noun as Noun).Gender;
                    gen     = (noun.SpellPart == UnTerminate.Перечисление) ? WordGender.They : gen;
                    wordStr = verb.GetVerb(gen, time);
                    break;
                }

                case Terminate.Прилагательное:
                {
                    var        adj  = (tword as Adjective);
                    var        noun = TSentence.First(word => word.SentencePart == Terminate.Существительное);
                    WordGender gen  = (noun as Noun).Gender;
                    gen     = (noun.SpellPart == UnTerminate.Перечисление) ? WordGender.They : gen;
                    wordStr = adj.GetAdjective(gen);
                    break;
                }

                case Terminate.Предлог:
                {
                    wordStr = (tword as Pretext).Name;
                    break;
                }

                case Terminate.Союз:
                {
                    wordStr = (tword as Union).Name;
                    break;
                }

                default:
                    break;
                }
                wordStr = (i > 0) ? wordStr : wordStr.First().ToString().ToUpper() + wordStr.Substring(1);
                wordStr = (tword == Dot || tword == Comma || i == 0) ? wordStr : " " + wordStr;
                builder.Append(wordStr);
            }
            return(builder.ToString());
        }
        private void CommentView_PreRender(object sender, System.EventArgs e)
        {
            string       entryId = (string)ViewState["entryId"];
            EntryIdCache ecache  = new EntryIdCache();

            ecache.Ensure(data);
            Control root = comments;

            DateTime found = new DateTime();

            foreach (EntryIdCacheEntry ece in ecache.Entries)
            {
                if (ece.EntryId.ToUpper() == entryId)
                {
                    found   = ece.Date;
                    entryId = ece.EntryId;
                    break;
                }
            }

            bool     obfuscateEmail = SiteConfig.GetSiteConfig().ObfuscateEmail;
            DayExtra extra          = data.GetDayExtra(found);

            extra.Load();

            foreach (DayEntry day in data.Days)
            {
                if (day.Date == found)
                {
                    day.Load();
                    foreach (Entry entry in day.Entries)
                    {
                        if (entry.EntryId == entryId)
                        {
                            EntryView entryView = (EntryView)LoadControl("EntryView.ascx");
                            entryView.Data  = data;
                            entryView.Entry = entry;
                            entryView.Extra = extra;
                            comments.Controls.Add(entryView);
                        }
                    }
                }
            }

            commentSpamGuard.Visible = SiteConfig.GetSiteConfig().CommentSpamGuard;
            if (SiteConfig.GetSiteConfig().CommentSpamGuard)
            {
                System.Security.Cryptography.RandomNumberGenerator r = System.Security.Cryptography.RandomNumberGenerator.Create();
                byte[] randomData = new byte[4];
                r.GetBytes(randomData);
                int code = 0;
                for (int i = 0; i < randomData.Length; i++)
                {
                    code += randomData[i];
                }
                code = code % SiteConfig.GetCommentWords().Length;
                securityWordImage.ImageUrl = BlogXUtils.RelativeToRoot("verifyimagegen.ashx?code=" + code);
                ViewState["spamCode"]      = code;
            }


            foreach (Comment c in extra.GetCommentsFor(entryId))
            {
                SingleCommentView view = (SingleCommentView)LoadControl("SingleCommentView.ascx");
                view.Comment        = c;
                view.ObfuscateEmail = obfuscateEmail;
                root.Controls.Add(view);
            }
        }
Esempio n. 15
0
 public static byte[] Encrypt_v15(System.Security.Cryptography.RSA rsa, System.Security.Cryptography.RandomNumberGenerator rng, byte[] M)
 {
     throw new NotImplementedException();
 }
Esempio n. 16
0
 public Random()
 {
     Generator = System.Security.Cryptography.RandomNumberGenerator.Create();
 }
Esempio n. 17
0
 public Random()
 {
     Generator = System.Security.Cryptography.RandomNumberGenerator.Create();
 }
 public RandomNumberGeneratorWrapper(System.Security.Cryptography.RandomNumberGenerator rng)
 {
     _rng = rng;
 }
Esempio n. 19
0
        public void GenerateKey(string strName, string strEmail, string strKeyType, int iKeySize, long lExpiration, string strPassphrase)
        {
            if (strKeyType == "ElGamal/DSA")
            {
                System.Security.Cryptography.RandomNumberGenerator rngRand = System.Security.Cryptography.RandomNumberGenerator.Create();

                // let's first create the encryption key
                BigInteger[][] biEncryptionKey = GenerateEncryptionKey(iKeySize);

                // now the signature key
                BigInteger[][] biSignatureKey = GenerateSignatureKey();

                PublicKeyPacket pkpSignatureKey = new PublicKeyPacket(false);
                pkpSignatureKey.Algorithm   = AsymAlgorithms.DSA;
                pkpSignatureKey.KeyMaterial = biSignatureKey[0];
                pkpSignatureKey.TimeCreated = DateTime.Now;
                pkpSignatureKey.Version     = PublicKeyPacketVersionNumbers.v4;

                SecretKeyPacket skpSignatureKey = new SecretKeyPacket(false);
                skpSignatureKey.SymmetricalAlgorithm = SymAlgorithms.AES256;
                skpSignatureKey.PublicKey            = pkpSignatureKey;
                skpSignatureKey.InitialVector        = new byte[CipherHelper.CipherBlockSize(SymAlgorithms.AES256)];
                rngRand.GetBytes(skpSignatureKey.InitialVector);
                skpSignatureKey.EncryptKeyMaterial(biSignatureKey[1], strPassphrase);
                skpSignatureKey.PublicKey = pkpSignatureKey;

                PublicKeyPacket pkpEncryptionKey = new PublicKeyPacket(true);
                pkpEncryptionKey.Algorithm   = AsymAlgorithms.ElGamal_Encrypt_Only;
                pkpEncryptionKey.KeyMaterial = biEncryptionKey[0];
                pkpEncryptionKey.TimeCreated = DateTime.Now;
                pkpEncryptionKey.Version     = PublicKeyPacketVersionNumbers.v4;

                SecretKeyPacket skpEncryptionKey = new SecretKeyPacket(true);
                skpEncryptionKey.SymmetricalAlgorithm = SymAlgorithms.AES256;
                skpEncryptionKey.PublicKey            = pkpEncryptionKey;
                skpEncryptionKey.InitialVector        = new byte[CipherHelper.CipherBlockSize(SymAlgorithms.AES256)];
                rngRand.GetBytes(skpEncryptionKey.InitialVector);
                skpEncryptionKey.EncryptKeyMaterial(biEncryptionKey[1], strPassphrase);
                skpEncryptionKey.PublicKey = pkpEncryptionKey;

                CertifiedUserID cuiUID = new CertifiedUserID();
                UserIDPacket    uipUID = new UserIDPacket();
                uipUID.UserID = strName.Trim() + " <" + strEmail.Trim() + ">";
                cuiUID.UserID = uipUID;
                SignaturePacket spSelfSig = new SignaturePacket();
                spSelfSig.Version       = SignaturePacketVersionNumbers.v4;
                spSelfSig.HashAlgorithm = HashAlgorithms.SHA1;
                spSelfSig.KeyID         = pkpSignatureKey.KeyID;
                spSelfSig.TimeCreated   = DateTime.Now;
                SignatureSubPacket sspPrimaryUserID = new SignatureSubPacket();
                sspPrimaryUserID.Type          = SignatureSubPacketTypes.PrimaryUserID;
                sspPrimaryUserID.PrimaryUserID = true;
                spSelfSig.AddSubPacket(sspPrimaryUserID, true);
                SignatureSubPacket sspPreferedSymAlgos = new SignatureSubPacket();
                sspPreferedSymAlgos.Type             = SignatureSubPacketTypes.PreferedSymmetricAlgorithms;
                sspPreferedSymAlgos.PreferedSymAlgos = new SymAlgorithms[] { SymAlgorithms.AES256, SymAlgorithms.AES192, SymAlgorithms.AES256, SymAlgorithms.CAST5, SymAlgorithms.Triple_DES };
                spSelfSig.AddSubPacket(sspPreferedSymAlgos, true);
                SignatureSubPacket sspPreferedHashAlgos = new SignatureSubPacket();
                sspPreferedHashAlgos.Type = SignatureSubPacketTypes.PreferedHashAlgorithms;
                sspPreferedHashAlgos.PreferedHashAlgos = new HashAlgorithms[] { HashAlgorithms.SHA1 };
                spSelfSig.AddSubPacket(sspPreferedHashAlgos, true);
                if (lExpiration != 0)
                {
                    SignatureSubPacket sspExpiration = new SignatureSubPacket();
                    sspExpiration.Type = SignatureSubPacketTypes.SignatureExpirationTime;
                    sspExpiration.SignatureExpirationTime = new DateTime(lExpiration);
                    spSelfSig.AddSubPacket(sspExpiration, true);
                }
                cuiUID.Certificates = new System.Collections.ArrayList();
                cuiUID.Sign(spSelfSig, skpSignatureKey, strPassphrase, pkpSignatureKey);

                CertifiedPublicSubkey cpsEncryptionKey = new CertifiedPublicSubkey();
                cpsEncryptionKey.Subkey = pkpEncryptionKey;
                cpsEncryptionKey.SignKeyBindingSignature(pkpSignatureKey, skpSignatureKey, strPassphrase, new DateTime(lExpiration), true);

                TransportablePublicKey tpkPublicKey = new TransportablePublicKey();
                tpkPublicKey.PrimaryKey = pkpSignatureKey;
                tpkPublicKey.SubKeys.Add(cpsEncryptionKey);
                tpkPublicKey.Certifications.Add(cuiUID);

                TransportableSecretKey tskSecretKey = new TransportableSecretKey();
                tskSecretKey.PrimaryKey = skpSignatureKey;
                tskSecretKey.SubKeys.Add(skpEncryptionKey);
                tskSecretKey.UserIDs.Add(uipUID);

                this.pkrKeyRing.AddPublicKey(tpkPublicKey);
                this.skrKeyRing.AddSecretKey(tskSecretKey);
                pkrKeyRing.Save();
                skrKeyRing.Save();

                // it's an RSA key
            }
            else if (strKeyType == "RSA")
            {
            }
        }
Esempio n. 20
0
 public static BigInteger GenerateRandom(int bits, System.Security.Cryptography.RandomNumberGenerator rng)
 {
     throw new NotImplementedException();
 }
Esempio n. 21
0
 /// <summary>Create a new instance of a random UUID generator, using a specific random number generator</summary>
 public Uuid64RandomGenerator(System.Security.Cryptography.RandomNumberGenerator generator)
 {
     m_rng = generator ?? System.Security.Cryptography.RandomNumberGenerator.Create();
 }
Esempio n. 22
0
 public void Randomize(System.Security.Cryptography.RandomNumberGenerator rng)
 {
 }
        // this method may get called MANY times so this is the one to optimize
        public virtual int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, ref byte[] outputBuffer, int outputOffset)
        {
            if (m_disposed)
            {
                throw new ObjectDisposedException("Object is disposed");
            }

            if (outputOffset + inputCount > outputBuffer.Length)
            {
                throw new System.Security.Cryptography.CryptographicException("Insufficient output buffer size.");
            }

            int offs = inputOffset;
            int full;

            // this way we don't do a modulo every time we're called
            // and we may save a division
            if (inputCount != BlockSizeByte)
            {
                // fill the last block with 0's. this doesn't matter for CFB
                if (((inputCount % BlockSizeByte) != 0) && ((algo.Mode == CipherMode.CFB) || (algo.Mode == CipherMode.OpenPGP_CFB)))
                {
                    byte[] oldInputBuffer = new byte[inputCount];
                    Array.Copy(inputBuffer, oldInputBuffer, inputCount);
                    if (algo.Mode == CipherMode.CFB)
                    {
                        inputBuffer = new byte[inputCount + (BlockSizeByte - (inputCount % BlockSizeByte))];
                    }
                    else
                    {
                        inputBuffer = new byte[inputCount + (BlockSizeByte - (inputCount % BlockSizeByte)) + 2];
                    }
                    outputBuffer = new byte[inputBuffer.Length];
                    Array.Copy(oldInputBuffer, 0, inputBuffer, 0, inputCount);
                    inputCount = inputBuffer.Length;
                }
                else if ((inputCount % BlockSizeByte) != 0)
                {
                    throw new System.Security.Cryptography.CryptographicException("Invalid input block size.");
                }
            }
            else
            {
                full = 1;
            }

            // OpenPGP needs some special treatment
            if (offs == 0 && algo.Mode == CipherMode.OpenPGP_CFB)
            {
                if (encrypt)
                {
                    // at first we have an encrypted random block
                    byte[] tmpInput  = new byte[BlockSizeByte];
                    byte[] tmp2Input = new byte[BlockSizeByte];
                    outputBuffer = new byte[outputBuffer.Length + BlockSizeByte + 2];
                    System.Security.Cryptography.RandomNumberGenerator rngIntro = System.Security.Cryptography.RandomNumberGenerator.Create();
                    rngIntro.GetBytes(tmpInput);
                    tmp2Input[0] = tmpInput[tmpInput.Length - 2];
                    tmp2Input[1] = tmpInput[tmpInput.Length - 1];
                    Transform(tmpInput, workout);
                    Array.Copy(workout, 0, outputBuffer, 0, BlockSizeByte);
                    outputOffset += BlockSizeByte;

                    //now the last 2 bytes
                    byte[] tmpWorkout = new byte[BlockSizeByte];
                    //tmp2Input.Initialize();
                    Transform(tmp2Input, tmpWorkout);
                    Array.Copy(tmpWorkout, 0, outputBuffer, outputOffset, 2);
                    outputOffset += 2;

                    // Load feedback-register with c3 - c10
                    Array.Copy(outputBuffer, 2, temp, 0, BlockSizeByte);
                }
                else
                {
                    Array.Copy(inputBuffer, offs, workBuff, 0, BlockSizeByte);
                    Transform(workBuff, workout);
                    Array.Copy(workout, 0, openPGPStart, 0, BlockSizeByte);
                    offs += BlockSizeByte;

                    byte[] tmpInput = new byte[BlockSizeByte];
                    tmpInput.Initialize();
                    Array.Copy(inputBuffer, offs, tmpInput, 0, 2);
                    Transform(tmpInput, workout);
                    Array.Copy(workout, 0, openPGPStart, BlockSizeByte, 2);
                    int x = openPGPStart.Length;
                    if ((openPGPStart[x - 1] != openPGPStart[x - 3]) || (openPGPStart[x - 2] != openPGPStart[x - 4]))
                    {
                        throw new System.Security.Cryptography.CryptographicException("Wrong Key!!");
                    }

                    // Load feedback-register with c3 - c[BS+2]
                    Array.Copy(inputBuffer, 2, temp, 0, BlockSizeByte);
                    offs += 2;
                }
            }

            full = (inputCount - offs) / BlockSizeByte;

            int total = 0;

            for (int i = 0; i < full; i++)
            {
                Array.Copy(inputBuffer, offs, workBuff, 0, BlockSizeByte);
                Transform(workBuff, workout);
                Array.Copy(workout, 0, outputBuffer, outputOffset, BlockSizeByte);
                offs         += BlockSizeByte;
                outputOffset += BlockSizeByte;
                total        += BlockSizeByte;
            }
            return(total);
        }
Esempio n. 24
0
        public static void Invoker()
        {
            double d = 3.9;
            int    i = Convert.ToInt32(d);//i==4


            int  thirty = Convert.ToInt32("1E", 16);  //30 Parse in hexadecimal
            uint five   = Convert.ToUInt32("101", 2); //5 Parse in binary

            Console.WriteLine(thirty);
            Console.WriteLine(five);

            {
                //Math
                Console.WriteLine("==============BigInteger===============");
                //BigInteger:BigInteger结构体是.NetFramework4.0新增的特殊值类型,它位于System.Numerics.dll的System.Numerics命名空间中。它可以表示任意大的整数而不会丢失精度。
                System.Numerics.BigInteger twentyfive = 25;
                Console.WriteLine(twentyfive);
                System.Numerics.BigInteger googol = System.Numerics.BigInteger.Pow(10, 100);//10的100次方
                Console.WriteLine(googol.ToString());
                //BigInteger重载了包括去余数(%)在内的所有算术运算符,还重载了顺序比较运算符
                //另一种创建Biginteger的方式是从字节进行创建。
                System.Security.Cryptography.RandomNumberGenerator ran = System.Security.Cryptography.RandomNumberGenerator.Create();
                byte[] bytes = new byte[32];
                ran.GetBytes(bytes);
                var bigNumber = new System.Numerics.BigInteger(bytes);
                Console.WriteLine(bigNumber);
                Console.WriteLine("==============Cmoplex===============");
                //Cmoplex结构体也是.NetFramework4.0新增的特殊值类型,它表示实部和虚部均为double类型的负数。
                var c1 = new System.Numerics.Complex(2, 3.5);
                Console.WriteLine(c1.Real);      //实部
                Console.WriteLine(c1.Imaginary); //虚部
                Console.WriteLine(c1.Phase);     //复数的相位
                Console.WriteLine(c1.Magnitude); //复数的量值
                Console.WriteLine(System.Numerics.Complex.Asin(c1));
                Console.WriteLine("==============Random===============");
                //Random类能够生成类型为byte、integer、或double的伪随机数序列。
                //使用Random之前需要将其序列化,并可以传递一个可选的种子参数来初始化随机数序列。使用相同的种子(在相同的CLR版本下)一定会产生相同序列的数字。这个特性在重现过程中非常有用:
                Random r1 = new Random(1);
                Random r2 = new Random(1);
                Console.WriteLine(r1.Next(100) + "," + r1.Next(100));
                Console.WriteLine(r2.Next(100) + "," + r2.Next(100));
                //若不需要重现性,那么创建Random时无需提供种子,此时将用当前系统时间来生成种子。
                /*由于系统时钟只有有限的粒度,因此两个创建时间非常接近(一般在10毫秒之内的)Random实例会产生相同值的序列。常用的方法是每当需要一个随机数时才序列化一个Random对象,而不是重用一个对象。声明单例的静态Random实例是一个不错的模式,但是在多线程环境下可能出现问题,因此Random对象并非线程安全的。*/
                System.Security.Cryptography.RandomNumberGenerator rand = System.Security.Cryptography.RandomNumberGenerator.Create();
                byte[] bytes2 = new byte[4];
                rand.GetBytes(bytes2);
                var o = BitConverter.ToInt32(bytes2, 0);
                Console.WriteLine(o);
            }



            //动态转换
            //{
            //    Type targetType = typeof(int);
            //    object source = "42";
            //    object result = Convert.ChangeType(source, targetType);
            //    Convert.ChangeType(source, targetType);
            //    Console.WriteLine(result);//42
            //    Console.WriteLine(result.GetType());//System.Int32
            //}
            //{
            //    CultureInfo culture = CultureInfo.CreateSpecificCulture("en-US");
            //    Type targetType = typeof(double);
            //    string source = "1,034,562.91";
            //    var result = Convert.ChangeType(source, targetType,culture);
            //    Console.WriteLine(result);//1034562.91
            //    Console.WriteLine(result.GetType());//System.Double

            //}
        }