public static string AESEncrypt(string saltString, string plainText)
        {
            if (secretKeyParameter == null)
            {
                secretKeyParameter = KeyGen(saltString);
            }
            string          empty  = string.Empty;
            IBufferedCipher cipher = CipherUtilities.GetCipher(ENCRYPTION_ALGORITHM + "/CBC/PKCS5PADDING");

            byte[]       array    = new byte[cipher.GetBlockSize()];
            SecureRandom instance = SecureRandom.GetInstance("SHA1PRNG");

            instance.NextBytes(array);
            ParametersWithIV parametersWithIV = new ParametersWithIV(secretKeyParameter, array);

            cipher.Init(forEncryption: true, parametersWithIV);
            int num = array.Length;

            byte[] array2 = cipher.DoFinal(Encoding.UTF8.GetBytes(plainText));
            Debug.Log("AESEncrypt:: IV as string: " + Convert.ToBase64String(parametersWithIV.GetIV()));
            Debug.Log("AESEncrypt:: encryptedByte as string: " + Convert.ToBase64String(array2));
            byte[] array3 = new byte[num + array2.Length];
            Array.Copy(parametersWithIV.GetIV(), 0, array3, 0, num);
            Array.Copy(array2, 0, array3, num, array2.Length);
            empty = Convert.ToBase64String(array3, Base64FormattingOptions.None);
            Debug.Log("AESEncrypt:: encryptedString: " + empty);
            return(empty);
        }
Example #2
0
        //public string PublicKeyBeforeSha256 { get; set; }
        //private string _privateKey;


        //public AsymmetricCipherKeyPair GenerateKeyPair()
        //{
        //    ECKeyPairGenerator keyPair = new ECKeyPairGenerator("EC");
        //    keyPair.Init(new KeyGenerationParameters(new SecureRandom(), 384));
        //    var pair = keyPair.GenerateKeyPair();

        //    //PublicKeyBeforeSha256 = GetPublicKeyStringRepresentation(pair.Public);
        //    //_privateKey = GetPrivateKeyStringRepresentation(pair.Private);

        //    return pair;
        //}


        /**
         * Generate a random private key that can be used with Secp256k1.
         */
        public static byte[] GeneratePrivateKey()
        {
            SecureRandom secureRandom = null;

            try
            {
                secureRandom =
                    SecureRandom.GetInstance(RANDOM_NUMBER_ALGORITHM, RANDOM_NUMBER_ALGORITHM_PROVIDER);
            }
            catch (Exception e)
            {
                Console.WriteLine("err");
            }

            BigInteger privateKeyCheck = BigInteger.Zero;
            // Bit of magic, move this maybe. This is the max key range.
            BigInteger maxKey =
                new BigInteger("00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364140", 16);

            // Generate the key, skipping as many as desired.
            byte[] privateKeyAttempt = new byte[32];
            secureRandom?.NextBytes(privateKeyAttempt);
            privateKeyCheck = new BigInteger(1, privateKeyAttempt);
            while (privateKeyCheck.CompareTo(BigInteger.Zero) == 0 ||
                   privateKeyCheck.CompareTo(maxKey) == 1)
            {
                secureRandom?.NextBytes(privateKeyAttempt);
                privateKeyCheck = new BigInteger(1, privateKeyAttempt);
            }

            return(privateKeyAttempt);
        }
Example #3
0
        public async static Task <TlsClientProtocol> PerformSSLHadshakeWithToken(ConnectionState connectionState, CancellationToken token)
        {
            byte[] random      = new byte[128];
            var    rngProvider = new System.Security.Cryptography.RNGCryptoServiceProvider();

            rngProvider.GetBytes(random);
            var secureRandomInstance = SecureRandom.GetInstance("SHA256PRNG");

            secureRandomInstance.SetSeed(random);

            TlsClientProtocol pkiClientProtocol = new TlsClientProtocol(secureRandomInstance);

            MyPKITlsClient pkiClient = new MyPKITlsClient();

            pkiClientProtocol.Connect(pkiClient);

            await SendSelectSslModuleApduAsync(connectionState, token);

            await SendSslResetApduAsync(connectionState, token);

            while (pkiClient.handshakeFinished != true)
            {
                int dataAvailable = pkiClientProtocol.GetAvailableOutputBytes();

                byte[] data = new byte[dataAvailable];

                pkiClientProtocol.ReadOutput(data, 0, dataAvailable);

                byte[] response = await SendHandshakeApduAsync(data, connectionState, token);

                pkiClientProtocol.OfferInput((byte[])response);
            }

            return(pkiClientProtocol);
        }
Example #4
0
        public static void StartGenerateKeypair(byte[] seed, GenCompleteEventHandler evt)
        {
            Thread genThread = new Thread(new ParameterizedThreadStart((o) =>
            {
                //create a random number generator using SHA512 algorithm
                SecureRandom rnd = SecureRandom.GetInstance(RANDOM_ALGO);
                rnd.SetSeed(seed);

                X9ECParameters curve      = TeleTrusTNamedCurves.GetByName(ECDSA_CURVE);
                ECDomainParameters domain = new ECDomainParameters(curve.Curve, curve.G, curve.N);

                //create the parameters for initializing the key pair generator using the brainpoolp384t1 curve
                ECKeyGenerationParameters parms = new ECKeyGenerationParameters(domain, rnd);

                //create and initialize the key pair generator
                ECKeyPairGenerator gen = new ECKeyPairGenerator("ECDSA");
                gen.Init(parms);

                //generate the key pair
                AsymmetricCipherKeyPair kp = gen.GenerateKeyPair();

                //trigger the event
                Xamarin.Forms.Device.BeginInvokeOnMainThread(() =>
                {
                    if (evt != null)
                    {
                        evt(kp);
                    }
                });
            }));

            genThread.Start();
        }
        public static RSAKey Generate()
        {
            try
            {
                RSAKey result = new RSAKey();
                IAsymmetricCipherKeyPairGenerator gen;
                KeyGenerationParameters           param;
                gen   = new RsaKeyPairGenerator();
                param = new RsaKeyGenerationParameters(
                    new BigInteger("3", 16),
                    SecureRandom.GetInstance("SHA1PRNG"),
                    2048,
                    80
                    );
                gen.Init(param);
                AsymmetricCipherKeyPair pair = gen.GenerateKeyPair();
                using (TextWriter textWriter = new StringWriter())
                {
                    PemWriter wr = new PemWriter(textWriter);
                    wr.WriteObject(pair.Private);
                    wr.Writer.Flush();
                    result.PrivatePEM = textWriter.ToString();
                }
                using (TextWriter textWriter = new StringWriter())
                {
                    PemWriter wr = new PemWriter(textWriter);
                    wr.WriteObject(pair.Public);
                    wr.Writer.Flush();
                    result.PublicPEM = textWriter.ToString();
                }
                using (StringReader sr = new StringReader(result.PublicPEM))
                {
                    PemReader        reader       = new PemReader(sr);
                    RsaKeyParameters r            = (RsaKeyParameters)reader.ReadObject();
                    byte[]           sshrsa_bytes = Encoding.Default.GetBytes("ssh-rsa");
                    byte[]           n            = r.Modulus.ToByteArray();
                    byte[]           e            = r.Exponent.ToByteArray();
                    string           buffer64;
                    using (MemoryStream ms = new MemoryStream()){
                        ms.Write(ToBytes(sshrsa_bytes.Length), 0, 4);
                        ms.Write(sshrsa_bytes, 0, sshrsa_bytes.Length);
                        ms.Write(ToBytes(e.Length), 0, 4);
                        ms.Write(e, 0, e.Length);
                        ms.Write(ToBytes(n.Length), 0, 4);
                        ms.Write(n, 0, n.Length);
                        ms.Flush();
                        buffer64 = Convert.ToBase64String(ms.ToArray());
                    }

                    result.PublicSSH = string.Format("ssh-rsa {0} generated-key", buffer64);
                }

                return(result);
            }
            catch (Org.BouncyCastle.Crypto.CryptoException ex)
            {
                throw ex;
            }
        }
Example #6
0
        public static string GenerateText(int size)
        {
            byte[]       textAsBytes  = new byte[size];
            SecureRandom secureRandom = SecureRandom.GetInstance("SHA256PRNG", true);

            secureRandom.NextBytes(textAsBytes);
            return(Base64.ToBase64String(textAsBytes));
        }
        public void TestSha256Prng()
        {
            SecureRandom random = SecureRandom.GetInstance("SHA256PRNG");

            random.SetSeed(SecureRandom.GetSeed(32));

            checkSecureRandom(random);
        }
        public void TestSha1Prng()
        {
            SecureRandom random = SecureRandom.GetInstance("SHA1PRNG");

            random.SetSeed(SecureRandom.GetSeed(20));

            checkSecureRandom(random);
        }
Example #9
0
        internal static byte[] CreateRandomSalt()
        {
            var random = SecureRandom.GetInstance("SHA256PRNG");
            var salt   = new byte[122];

            random.NextBytes(salt);
            return(salt);
        }
Example #10
0
        public void TestThreadedSeed()
        {
            SecureRandom random = SecureRandom.GetInstance("SHA1PRNG", false);

            random.SetSeed(new ThreadedSeedGenerator().GenerateSeed(20, false));

            CheckSecureRandom(random);
        }
Example #11
0
        public RSA(int length = 2048)
        {
            KeyLength = length;
            var gen = new RsaKeyPairGenerator();

            gen.Init(new KeyGenerationParameters(SecureRandom.GetInstance("SHA256PRNG", true), length));
            _KeyPair = gen.GenerateKeyPair();
        }
        /// <summary>
        /// Builds a SecureRandom with seed filled in.
        /// </summary>
        /// <returns></returns>
        public static SecureRandom GetSecureRandom()
        {
            SecureRandom secureRandom = SecureRandom.GetInstance("SHA1PRNG", false);

            byte[] seed = new byte[1024];
            secureRandom.NextBytes(seed);
            secureRandom.SetSeed(seed);
            return(secureRandom);
        }
Example #13
0
        private void Generate()
        {
            SecureRandom random = SecureRandom.GetInstance("SHA1PRNG");

            //
            // Generate a master key
            //
            IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator("ECDSA");

            keyGen.Init(new ECKeyGenerationParameters(SecObjectIdentifiers.SecP256r1, random));

            AsymmetricCipherKeyPair kpSign = keyGen.GenerateKeyPair();

            PgpKeyPair ecdsaKeyPair = new PgpKeyPair(PublicKeyAlgorithmTag.ECDsa, kpSign, DateTime.UtcNow);

            //
            // Generate an encryption key
            //
            keyGen = GeneratorUtilities.GetKeyPairGenerator("ECDH");
            keyGen.Init(new ECKeyGenerationParameters(SecObjectIdentifiers.SecP256r1, random));

            AsymmetricCipherKeyPair kpEnc = keyGen.GenerateKeyPair();

            PgpKeyPair ecdhKeyPair = new PgpKeyPair(PublicKeyAlgorithmTag.ECDH, kpEnc, DateTime.UtcNow);

            //
            // Generate a key ring
            //
            char[] passPhrase = "test".ToCharArray();
            PgpKeyRingGenerator keyRingGen = new PgpKeyRingGenerator(PgpSignature.PositiveCertification, ecdsaKeyPair,
                                                                     "*****@*****.**", SymmetricKeyAlgorithmTag.Aes256, passPhrase, true, null, null, random);

            keyRingGen.AddSubKey(ecdhKeyPair);

            PgpPublicKeyRing pubRing = keyRingGen.GeneratePublicKeyRing();

            // TODO: add check of KdfParameters
            DoBasicKeyRingCheck(pubRing);

            PgpSecretKeyRing secRing = keyRingGen.GenerateSecretKeyRing();

            PgpPublicKeyRing pubRingEnc = new PgpPublicKeyRing(pubRing.GetEncoded());

            if (!Arrays.AreEqual(pubRing.GetEncoded(), pubRingEnc.GetEncoded()))
            {
                Fail("public key ring encoding failed");
            }

            PgpSecretKeyRing secRingEnc = new PgpSecretKeyRing(secRing.GetEncoded());

            if (!Arrays.AreEqual(secRing.GetEncoded(), secRingEnc.GetEncoded()))
            {
                Fail("secret key ring encoding failed");
            }

            PgpPrivateKey pgpPrivKey = secRing.GetSecretKey().ExtractPrivateKey(passPhrase);
        }
        /// <summary>
        /// Encrypts and encodes the private key.
        /// </summary>
        /// <param name="key">The private key.</param>
        /// <param name="passPhrase">The pass phrase to encrypt the private key.</param>
        /// <returns>The encrypted private key.</returns>
        public static string ToEncryptedPrivateKeyString(AsymmetricKeyParameter key, string passPhrase)
        {
            var salt         = new byte[16];
            var secureRandom = SecureRandom.GetInstance("SHA256PRNG");

            secureRandom.SetSeed(SecureRandom.GetSeed(16));               //See Bug #135
            secureRandom.NextBytes(salt);

            return(Convert.ToBase64String(PrivateKeyFactory.EncryptKey(keyEncryptionAlgorithm, passPhrase.ToCharArray(), salt, 10, key)));
        }
Example #15
0
        /// <summary>
        /// Generates a KeyPair
        /// </summary>
        /// <returns></returns>
        public static AsymmetricCipherKeyPair GeneratePrivateKey()
        {
            Ed25519KeyPairGenerator d = new Ed25519KeyPairGenerator();

            d.Init(new Ed25519KeyGenerationParameters(SecureRandom.GetInstance(Ed25519_ALGO)));

            AsymmetricCipherKeyPair keyPair = d.GenerateKeyPair();

            return(keyPair);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="KeyGenerator"/> class
        /// with the specified key size and seed.
        /// </summary>
        /// <remarks>Following key sizes are supported:
        /// - 192
        /// - 224
        /// - 239
        /// - 256 (default)
        /// - 384
        /// - 521</remarks>
        /// <param name="keySize">The key size.</param>
        /// <param name="seed">The seed.</param>
        public KeyGenerator(int keySize, byte[] seed)
        {
            var secureRandom = SecureRandom.GetInstance("SHA256PRNG");

            secureRandom.SetSeed(seed);

            var keyParams = new KeyGenerationParameters(secureRandom, keySize);

            keyGenerator = new ECKeyPairGenerator();
            keyGenerator.Init(keyParams);
        }
Example #17
0
        /// <summary>
        /// Requests that the specified Purchasable be purchased on behalf of the current user.
        /// The IAP client service is responsible for identifying the user and requesting credentials as appropriate,
        /// as well as providing all of the UI for the purchase flow. When purchases are successful, a Product object
        /// is returned that describes the product that was purchased.
        /// </summary>
        /// <param name="product">The Purchasable object that describes the item to be purchased.</param>
        /// <returns>Returns true if the purchase was successful.</returns>
        public async Task <bool> RequestPurchaseAsync(Product product)
        {
            if (ReferenceEquals(product, null))
            {
                throw new ArgumentNullException("product");
            }

            var tcs = new TaskCompletionSource <bool>();

            // Create the Purchasable object from the supplied product
            var sr = SecureRandom.GetInstance("SHA1PRNG");

            // This is an ID that allows you to associate a successful purchase with
            // it's original request. The server does nothing with this string except
            // pass it back to you, so it only needs to be unique within this instance
            // of your app to allow you to pair responses with requests.
            var uniqueId = sr.NextLong().ToString("X");

            JSONObject purchaseRequest = new JSONObject();

            purchaseRequest.Put("uuid", uniqueId);
            purchaseRequest.Put("identifier", product.Identifier);
            var purchaseRequestJson = purchaseRequest.ToString();

            byte[] keyBytes = new byte[16];
            sr.NextBytes(keyBytes);
            var key = new SecretKeySpec(keyBytes, "AES");

            byte[] ivBytes = new byte[16];
            sr.NextBytes(ivBytes);
            var iv = new IvParameterSpec(ivBytes);

            Cipher cipher = Cipher.GetInstance("AES/CBC/PKCS5Padding", "BC");

            cipher.Init(CipherMode.EncryptMode, key, iv);
            var payload = cipher.DoFinal(Encoding.UTF8.GetBytes(purchaseRequestJson));

            cipher = Cipher.GetInstance("RSA/ECB/PKCS1Padding", "BC");
            cipher.Init(CipherMode.EncryptMode, _publicKey);
            var encryptedKey = cipher.DoFinal(keyBytes);

            var purchasable = new Purchasable(
                product.Identifier,
                Convert.ToBase64String(encryptedKey, Base64FormattingOptions.None),
                Convert.ToBase64String(ivBytes, Base64FormattingOptions.None),
                Convert.ToBase64String(payload, Base64FormattingOptions.None));

            var listener = new PurchaseListener(tcs, _publicKey, product, uniqueId);

            RequestPurchase(purchasable, listener);
            // No timeout for purchase as it shows a user dialog
            return(await tcs.Task);
        }
Example #18
0
        private void GenerateKeyPair()
        {
            var keyGen       = new ECKeyPairGenerator("ECDSA");
            var secureRandom = SecureRandom.GetInstance("SHA1PRNG");
            var ecSpec       = X9ObjectIdentifiers.Prime192v1;

            keyGen.Init(new ECKeyGenerationParameters(ecSpec, secureRandom));
            var keyPair = keyGen.GenerateKeyPair();

            PublicKey  = keyPair.Public as ECPublicKeyParameters;
            PrivateKey = keyPair.Private as ECPrivateKeyParameters;
        }
Example #19
0
        public static X509Certificate2 GetDotnetCertificate(this Pkcs12Store store)
        {
            var stream   = new MemoryStream();
            var password = "******";

            store.Save(stream, password.ToCharArray(), SecureRandom.GetInstance("SHA256PRNG"));

            var dotnetCertificate = new X509Certificate2(stream.ToArray(), password,
                                                         X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);

            return(dotnetCertificate);
        }
Example #20
0
        public void TestSha1PrngBackward()
        {
            byte[] seed = Encoding.ASCII.GetBytes("backward compatible");

            SecureRandom sx = new SecureRandom(seed);
            SecureRandom sy = SecureRandom.GetInstance("SHA1PRNG", false); sy.SetSeed(seed);

            byte[] bx = new byte[128]; sx.NextBytes(bx);
            byte[] by = new byte[128]; sy.NextBytes(by);

            Assert.IsTrue(Arrays.AreEqual(bx, by));
        }
Example #21
0
 /// <summary>
 /// Generates a key pair 
 /// </summary>
 void GenerateKeyPair()
 {
     ECKeyPairGenerator keyGen = new ECKeyPairGenerator("ECDSA");
     SecureRandom secureRandom = SecureRandom.GetInstance("SHA1PRNG");
     Org.BouncyCastle.Asn1.X9.X9ECParameters ecp = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp192k1");//("prime192v1");//("secp224k1");
     ECDomainParameters ecSpec = new ECDomainParameters(ecp.Curve, ecp.G, ecp.N, ecp.H, ecp.GetSeed());
     ECKeyGenerationParameters ecKeyGenParams = new ECKeyGenerationParameters(ecSpec, secureRandom);
     keyGen.Init(ecKeyGenParams);
     AsymmetricCipherKeyPair keyPair = keyGen.GenerateKeyPair();
     PrivateKey = keyPair.Private as ECPrivateKeyParameters;
     PublicKey = keyPair.Public as ECPublicKeyParameters;
 }
Example #22
0
        public static String GenerateText(int size)

        {
            var textAsBytes = new Byte[size];

            var secureRandom = SecureRandom.GetInstance("SHA256PRNG", true);



            secureRandom.NextBytes(textAsBytes);

            return(Convert.ToBase64String(textAsBytes));
        }
Example #23
0
        public async static Task EstablishSRPChannelAsync(ConnectionState connectionState, CancellationToken token)
        {
            string keyAsString;

            Settings.GetSrpKey(out keyAsString);
            byte[] key = keyAsString.ConvertHexStringToByteArray();

            byte[] random      = new byte[128];
            var    rngProvider = new System.Security.Cryptography.RNGCryptoServiceProvider();

            rngProvider.GetBytes(random);
            var secureRandomInstance = SecureRandom.GetInstance("SHA256PRNG");

            secureRandomInstance.SetSeed(random);

            TlsClientProtocol srpClientProtocol = new TlsClientProtocol(secureRandomInstance);

            var srpClient = new MySrpTlsClient(Encoding.ASCII.GetBytes("user"), key);

            srpClientProtocol.Connect(srpClient);

            var stream = connectionState.client.GetStream();

            byte[] inputBuffer = new byte[4096];

            while (srpClient.handshakeFinished != true)
            {
                int dataAvailable = srpClientProtocol.GetAvailableOutputBytes();

                if (dataAvailable != 0)
                {
                    byte[] data = new byte[dataAvailable];

                    srpClientProtocol.ReadOutput(data, 0, dataAvailable);

                    await stream.WriteAsync(data, 0, dataAvailable, token);
                }

                int bytesReceived = await stream.ReadAsync(inputBuffer, 0, inputBuffer.Length, token);

                if (bytesReceived != 0)
                {
                    byte[] truncatedInputBuffer = new byte[bytesReceived];
                    Array.Copy(inputBuffer, 0, truncatedInputBuffer, 0, bytesReceived);

                    srpClientProtocol.OfferInput(truncatedInputBuffer);
                }
            }

            connectionState.srpClientProtocol = srpClientProtocol;
        }
Example #24
0
 public static bool getSecureRandomBytes(byte[] secureBytesArray)
 {
     if ((null != secureBytesArray) && (0 != secureBytesArray.Length))
     {
         try
         {
             SecureRandom ranGen = SecureRandom.GetInstance("SHA1PRNG");
             ranGen.NextBytes(secureBytesArray);
             return(true);
         }
         catch (NoSuchAlgorithmException) { }
     }
     return(false);
 }
 /// <summary>
 /// encryption random iv.
 /// </summary>
 /// <param name="size">iv length</param>
 /// <returns>encryption the byte array.</returns>
 public static sbyte[] GetIvByte(int size)
 {
     try
     {
         SecureRandom secureRandom = SecureRandom.GetInstance("SHA1PRNG");
         sbyte[]      bytes        = new sbyte[size];
         secureRandom.NextBytes((byte[])(Array)bytes);
         return(bytes);
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
         throw;
     }
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="BouncyKeyGenerator"/> class
        /// with the specified key size and seed.
        /// </summary>
        /// <remarks>Following key sizes are supported:
        /// - 192
        /// - 224
        /// - 239
        /// - 256 (default)
        /// - 384
        /// - 521</remarks>
        /// <param name="keySize">The key size.</param>
        /// <param name="seed">The seed.</param>
        public BouncyKeyGenerator(int keySize, byte[] seed)
        {
            var secureRandom = SecureRandom.GetInstance("SHA256PRNG");

            if (seed == null || seed.Length == 0)
            {
                seed = secureRandom.GenerateSeed(32);
            }
            secureRandom.SetSeed(seed);

            var keyParams = new KeyGenerationParameters(secureRandom, keySize);

            keyGenerator = new ECKeyPairGenerator();
            keyGenerator.Init(keyParams);
        }
Example #27
0
    //static initializer


    static AuthenticationHelper()
    {
        SECURE_RANDOM = SecureRandom.GetInstance("SHA1PRNG");

        HashAlgorithm messageDigest = THREAD_MESSAGE_DIGEST;

        byte[] nArr    = N.ToByteArray();
        byte[] gArr    = g.ToByteArray();
        byte[] content = new byte[nArr.Length + gArr.Length];
        Buffer.BlockCopy(nArr, 0, content, 0, nArr.Length);
        Buffer.BlockCopy(gArr, 0, content, nArr.Length, gArr.Length);
        byte[] digest = messageDigest.ComputeHash(content);
        k = new BigInteger(1, digest);

        Console.WriteLine();
    }
Example #28
0
        /// <summary>
        /// Initializes a new instance of the <see cref="KeyGenerator"/> class
        /// with the specified key size and seed.
        /// </summary>
        /// <remarks>Following key sizes are supported:
        /// - 192
        /// - 224
        /// - 239
        /// - 256 (default)
        /// - 384
        /// - 521</remarks>
        /// <param name="keySize">The key size.</param>
        /// <param name="seed">The seed.</param>
        public KeyGenerator(SupportedKeySizes keySize = SupportedKeySizes.KeySize256, byte[]?seed = null)
        {
            var secureRandom = SecureRandom.GetInstance("SHA256PRNG");

            if (seed is null)
            {
                secureRandom.GenerateSeed(32);
            }
            else
            {
                secureRandom.SetSeed(seed);
            }

            var keyParams = new KeyGenerationParameters(secureRandom, (int)keySize);

            keyGenerator = new ECKeyPairGenerator();
            keyGenerator.Init(keyParams);
        }
Example #29
0
        public override void PerformTest()
        {
            SecureRandom rand = SecureRandom.GetInstance("SHA1PRNG");

            doTestPadding(new Pkcs7Padding(), rand,
                          Hex.Decode("ffffff0505050505"),
                          Hex.Decode("0000000004040404"));

            Pkcs7Padding padder = new Pkcs7Padding();

            try
            {
                padder.PadCount(new byte[8]);

                Fail("invalid padding not detected");
            }
            catch (InvalidCipherTextException e)
            {
                if (!"pad block corrupted".Equals(e.Message))
                {
                    Fail("wrong exception for corrupt padding: " + e);
                }
            }

            doTestPadding(new ISO10126d2Padding(), rand,
                          null,
                          null);

            doTestPadding(new X923Padding(), rand,
                          null,
                          null);

            doTestPadding(new TbcPadding(), rand,
                          Hex.Decode("ffffff0000000000"),
                          Hex.Decode("00000000ffffffff"));

            doTestPadding(new ZeroBytePadding(), rand,
                          Hex.Decode("ffffff0000000000"),
                          null);

            doTestPadding(new ISO7816d4Padding(), rand,
                          Hex.Decode("ffffff8000000000"),
                          Hex.Decode("0000000080000000"));
        }
Example #30
0
        public override void SetConf(Configuration conf)
        {
            this.conf = conf;
            provider  = conf.Get(CommonConfigurationKeysPublic.HadoopSecurityCryptoJceProviderKey
                                 );
            string secureRandomAlg = conf.Get(CommonConfigurationKeysPublic.HadoopSecurityJavaSecureRandomAlgorithmKey
                                              , CommonConfigurationKeysPublic.HadoopSecurityJavaSecureRandomAlgorithmDefault);

            try
            {
                random = (provider != null) ? SecureRandom.GetInstance(secureRandomAlg, provider)
                                         : SecureRandom.GetInstance(secureRandomAlg);
            }
            catch (GeneralSecurityException e)
            {
                Log.Warn(e.Message);
                random = new SecureRandom();
            }
        }