public static Audience AddAudience(string name) { var clientId = Guid.NewGuid().ToString("N"); var key = new byte[32]; RNGCryptoServiceProvider.Create().GetBytes(key); var base64Secret = TextEncodings.Base64Url.Encode(key); Audience newAudience = new Audience { ClientId = clientId, Base64Secret = base64Secret, Name = name }; AudiencesList.TryAdd(clientId, newAudience); return(newAudience); }
public void SignVerifyTest() { RandomNumberGenerator random = RNGCryptoServiceProvider.Create(); byte[] bPriKey = new byte[32]; random.GetBytes(bPriKey); byte[] bExpPriKey = Ed25519.ExpandedPrivateKeyFromSeed(bPriKey); byte[] bPubKey = Ed25519.PublicKeyFromSeed(bPriKey); byte[] msg = new byte[] { 0x1, 0x2, 0x3, 0x4 }; byte[] sign = Ed25519.Sign(msg, bExpPriKey); Assert.True(Ed25519.Verify(sign, msg, bPubKey)); }
static void Main(string[] args) { var bytes = new byte[64]; RNGCryptoServiceProvider.Create().GetBytes(bytes); Console.WriteLine(string.Join("", bytes.Select(b => b.ToString("x2")))); var encoded = Base91Encoder.Encode(bytes); Console.WriteLine(Encoding.UTF8.GetString(encoded)); Console.WriteLine(encoded.Length); var decoded = Base91Encoder.Decode(encoded); Console.WriteLine(Encoding.UTF8.GetString(decoded)); Console.WriteLine(decoded.Length); }
private static string Secret() { string secret = ""; byte[] buffer = new byte[9]; using (RandomNumberGenerator rng = RNGCryptoServiceProvider.Create()) { rng.GetBytes(buffer); } secret = Convert.ToBase64String(buffer).Substring(0, 10).Replace('/', '0').Replace('+', '1'); var enc = Base32Encoder.Encode(Encoding.ASCII.GetBytes(secret)); return(enc); }
public string GenerateSecret() { var buffer = new byte[9]; using (var rng = RNGCryptoServiceProvider.Create()) { rng.GetBytes(buffer); } var secret = Convert.ToBase64String(buffer).Substring(0, 10).Replace('/', '0').Replace('+', '1'); var encoded = Base32Encoding.Encode(Encoding.ASCII.GetBytes(secret)); return(encoded); }
public EncryptedSocket(EncryptionTypes allowedEncryption) { random = RNGCryptoServiceProvider.Create(); hasher = HashAlgoFactory.Create <SHA1>(); GenerateX(); GenerateY(); InitialPayload = BufferManager.EmptyBuffer; RemoteInitialPayload = BufferManager.EmptyBuffer; bytesReceived = 0; SetMinCryptoAllowed(allowedEncryption); }
public static Audience GenerateAudience(string name) { //"N" -> 32 digits not seperated and not in braces. //"D" -> 32 digits seperated by hyphens. //"B" -> 32 digits seperated by hyphens and enclosed in braces. var clientId = Guid.NewGuid().ToString("N"); var key = new byte[32]; RNGCryptoServiceProvider.Create().GetBytes(key); var base64secret = TextEncodings.Base64Url.Encode(key); return(new Audience { Name = name, ClientId = clientId, Base64Secret = base64secret }); }
public static Audience AddAudience(string name) { var clientId = Guid.NewGuid().ToString("N"); var key = new byte[32]; RNGCryptoServiceProvider.Create().GetBytes(key); var secret = TextEncodings.Base64Url.Encode(key); var audience = new Audience() { ClientID = clientId, ClientName = name, Base64Secret = secret }; Audiencelist.TryAdd(clientId, audience); return(audience); }
public UserSessionService() { RandomNumberGenerator rng = RNGCryptoServiceProvider.Create(); byte[] data = new byte[16]; rng.GetBytes(data); SHA256 sha = SHA256.Create(); byte[] hash = sha.ComputeHash(data); _sessionId = Convert.ToBase64String(hash); _cultureInfo = Thread.CurrentThread.CurrentCulture; }
static void Main(string[] args) { var key = new byte[32]; RNGCryptoServiceProvider.Create().GetBytes(key); var base64Secret = Convert.ToBase64String(key); var clientId = RandomString(32); Console.WriteLine("JWT secret:"); Console.WriteLine(base64Secret); Console.WriteLine("ClientID"); Console.WriteLine(clientId); Console.ReadLine(); }
/// <summary> Hide the constructor for the Singleton pattern.</summary> public Randomizer() { string algorithm = Esapi.SecurityConfiguration().RandomAlgorithm; try { //Todo: Right now algorithm is ignored randomNumberGenerator = RNGCryptoServiceProvider.Create(); } catch (Exception e) { // Can't throw an exception from the constructor, but this will get // it logged and tracked new EncryptionException("Error creating randomizer", "Can't find random algorithm " + algorithm, e); } }
private static async Task <string> GetKey() { var key = await SecureStorage.GetAsync("encryption_key"); if (key != null) { return(key); } var newkey = new byte[16]; RNGCryptoServiceProvider.Create().GetBytes(newkey); await SecureStorage.SetAsync("encryption_key", Convert.ToBase64String(newkey)); return(Convert.ToBase64String(newkey)); }
public static string GetRandomHex(int length) { RandomNumberGenerator r = RNGCryptoServiceProvider.Create(); byte[] data = new byte[length]; r.GetBytes(data); StringBuilder sBuilder = new StringBuilder(); for (int i = 0; i < data.Length; i++) { sBuilder.Append(data[i].ToString("x2")); } return(sBuilder.ToString()); }
public static AppClient AddClient(string name) { var clientId = Guid.NewGuid().ToString("N"); var key = new byte[32]; RNGCryptoServiceProvider.Create().GetBytes(key); var base64Secret = Convert.ToBase64String(key); AppClient newAudience = new AppClient { ClientId = clientId, Base64Secret = base64Secret, Name = name }; AppClientsList.TryAdd(clientId, newAudience); return(newAudience); }
public static Audience AddAudience(string name) { var clientId = Guid.NewGuid().ToString("N"); var key = new byte[32]; RNGCryptoServiceProvider.Create().GetBytes(key); var base64Secret = "UHxNtYMRYwvfpO1dS5pWLKL0M2DgOj40EbN4SoBWgfc"; Audience newAudience = new Audience { ClientId = clientId, Base64Secret = base64Secret, Name = name }; AudiencesList.TryAdd(clientId, newAudience); return(newAudience); }
public void CreateTestNetAccount() { RandomNumberGenerator random = RNGCryptoServiceProvider.Create(); byte[] bPriKey = new byte[32]; random.GetBytes(bPriKey); byte[] bExpPriKey = Ed25519.ExpandedPrivateKeyFromSeed(bPriKey); byte[] bPubKey = Ed25519.PublicKeyFromSeed(bPriKey); string addr = Account.Create(bPubKey, NetType.Test_Net); NetType netType = NetType.Public_Net; bool bOk = Account.Verify(addr, out netType); Assert.True(bOk && netType == NetType.Test_Net); }
private int randomPosition() { byte[] intPick = new byte[4]; RNGCryptoServiceProvider.Create().GetBytes(intPick); if (BitConverter.IsLittleEndian) { Array.Reverse(intPick); } int pick = BitConverter.ToInt32(intPick, 0); pick %= 128; if (pick < 0) { pick += 128; } return(pick); }
/// <summary> /// Generates a new crypto random salt of 32bytes. /// </summary> /// <returns>32 crypto random bytes</returns> private static string GetNewSalt() { RandomNumberGenerator rng = RNGCryptoServiceProvider.Create(); byte[] saltBuffer = new byte[32]; rng.GetBytes(saltBuffer); StringBuilder builder = new StringBuilder(); foreach (byte element in saltBuffer) { builder.Append(element.ToString("X2")); } return(builder.ToString()); }
public bool Authenticate() { string secretCode; //if two factor authentication was never used before, new secret code is generated and qr code and manual setup code are shown to the user, otherwise secret code is extracted if (!AlreadySetUp()) { byte[] buffer = new byte[9]; using (RandomNumberGenerator rng = RNGCryptoServiceProvider.Create()) { rng.GetBytes(buffer); } secretCode = Convert.ToBase64String(buffer).Substring(0, 10).Replace('/', '0').Replace('+', '1'); //setup form is shown(if it's closed by 'X' button, authentication fails) using (var setupform = new TwoFactorSetup(AppName(), AppInfo(), secretCode, timeout)) { var result = setupform.ShowDialog(); if (result != DialogResult.OK) { return(false); } } } else { secretCode = GetSecretCode(); } //authentication form is shown and login is successful if entered code is correct using (var authform = new AuthenticatorForm(secretCode)) { var result = authform.ShowDialog(); if (result == DialogResult.OK) { if (!AlreadySetUp()) { SetSecretCode(secretCode); } return(true); } else { return(false); } } }
public ActionResult ShowTwoFactorSecret() { byte[] buffer = new byte[9]; using (RandomNumberGenerator rng = RNGCryptoServiceProvider.Create()) { rng.GetBytes(buffer); } // Generates a 10 character string of A-Z, a-z, 0-9 // Don't need to worry about any = padding from the // Base64 encoding, since our input buffer is divisible by 3 var enc = new Base32Encoder().Encode(Encoding.ASCII.GetBytes(Convert.ToBase64String(buffer).Substring(0, 10).Replace('/', '0').Replace('+', '1'))); return(View(new TwoFactorSecret { EncodedSecret = enc })); }
public static WebApplicationAccess GrantApplication(string name) { var clientId = Guid.NewGuid().ToString("N"); var key = new byte[32]; RNGCryptoServiceProvider.Create().GetBytes(key); var base64Secret = TextEncodings.Base64Url.Encode(key); var accessKey = new byte[32]; RNGCryptoServiceProvider.Create().GetBytes(key); var accessKeyText = TextEncodings.Base64Url.Encode(key); WebApplicationAccess newWebApplication = new WebApplicationAccess { ClientId = clientId, SecretKey = base64Secret, AccessKey = accessKeyText, ApplicationName = name }; WebApplicationAccessList.TryAdd(clientId, newWebApplication); return(newWebApplication); }
public static Audience AddAudience(string name) { var clientId = Guid.NewGuid().ToString("N"); var key = new byte[32]; RNGCryptoServiceProvider.Create().GetBytes(key); var base64Secret = TextEncodings.Base64Url.Encode(key); Audience newAudience = new Audience { ClientId = clientId, Base64Secret = base64Secret, Name = name }; // TODO: add other properties (see Audience entity). These properties could also be assigned as parameters in AddAudience method db.Audiences.Add(newAudience); db.SaveChanges(); return(newAudience); }
private string RandomGreetings() { var names = new string[] { "D34Dspy", "Sh8dow", "striek", "Atex", "xeno", "polivilas", "B74k", "Daax", "Janck7", "KN4CK3R", "patrik", "AestheticJunk", "Geertje123", "Puddin Poppin", "KingRain", "SeanGhost117", "sk0r", "Slayer", "Zooom" }; var random = new byte[names.Length]; RNGCryptoServiceProvider.Create().GetBytes(random); var list = new List <string>(names); var order = random.Select(x => { var idx = x % list.Count; var name = list[idx]; list.RemoveAt(idx); return(name); }); return(string.Join(", ", order.ToArray())); }
/// <summary> /// 获取随机密码(由英文字母和数字构成) /// </summary> /// <param name="passwordLength">密码长度</param> /// <param name="isLower">结果是否小写</param> /// <returns></returns> public virtual String GetRandomPassword(int passwordLength, Boolean isLower) { String charList = isLower ? "abcdefghijklmnopqrstuvwxyz0123456789" : "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; byte[] buffer = new byte[passwordLength]; RNGCryptoServiceProvider.Create().GetBytes(buffer); char[] chars = new char[passwordLength]; int charCount = charList.Length; for (int i = 0; i < passwordLength; i++) { chars[i] = charList[(int)buffer[i] % charCount]; } return(new string( chars )); }
public static string CreateOTP(YubikeySettings key, Form1 form) { string tokenID = ModHex.Encode(key.TokenID); // Assemble key unencrypted data byte[] keyBytes = new byte[16]; for (int i = 0; i < key.PrivateID.Length; ++i) { keyBytes[i] = key.PrivateID[i]; } keyBytes[6] = (byte)(key.SessionCounter & 0xff); keyBytes[7] = (byte)((key.SessionCounter >> 8) & 0xff); form.SessionCounter = key.SessionCounter.ToString(); TimeSpan diff = DateTime.Now - key.StartTime; int timer = (int)((((uint)(diff.TotalSeconds / TS_SEC) & 0x00FFFFFF) + key.TimeStamp) & 0x00FFFFFF); form.Timestamp = timer.ToString(); keyBytes[8] = (byte)(timer & 0xff); keyBytes[9] = (byte)((timer >> 8) & 0xff); keyBytes[10] = (byte)((timer >> 16) & 0xff); keyBytes[11] = key.UseCounter++; form.UseCounter = keyBytes[11].ToString(); byte[] buffer = new byte[2]; RNGCryptoServiceProvider.Create().GetBytes(buffer); form.Random = (((int)buffer[1] << 8) + (int)buffer[0]).ToString(); keyBytes[12] = buffer[0]; keyBytes[13] = buffer[1]; CRC(keyBytes); using (Rijndael aes = Rijndael.Create()) { aes.Padding = PaddingMode.None; aes.Mode = CipherMode.ECB; using (ICryptoTransform xform = aes.CreateEncryptor(key.Secret, new byte[16])) { byte[] plainBytes = new byte[16]; xform.TransformBlock(keyBytes, 0, keyBytes.Length, plainBytes, 0); string otp = tokenID + ModHex.Encode(plainBytes); return(otp); } } }
public static Audience AddAudience(string name) { var clientId = Guid.NewGuid().ToString("N"); var key = new byte[32]; RNGCryptoServiceProvider.Create().GetBytes(key); var base64Secret = TextEncodings.Base64Url.Encode(key); var db = ApplicationDbContext.Create(); Audience newAudience = new Audience { ClientId = clientId, Base64Secret = base64Secret, Name = name }; db.Audiences.Add(newAudience); db.SaveChangesAsync(); return(newAudience); }
/// <summary> /// Public constructor. /// </summary> public Encryptor() { // FIXME: AAA - need support for key and salt changing. What's best interface? byte[] salt = Esapi.SecurityConfiguration().MasterSalt; string pass = Esapi.SecurityConfiguration().MasterPassword; // setup algorithms encryptAlgorithm = Esapi.SecurityConfiguration().EncryptionAlgorithm; signatureAlgorithm = Esapi.SecurityConfiguration().DigitalSignatureAlgorithm; randomAlgorithm = Esapi.SecurityConfiguration().RandomAlgorithm; hashAlgorithm = Esapi.SecurityConfiguration().HashAlgorithm; try { // Set up encryption and decryption SymmetricAlgorithm symmetricAlgorithm = SymmetricAlgorithm.Create(encryptAlgorithm); symmetricAlgorithm.GenerateIV(); iv = symmetricAlgorithm.IV; symmetricAlgorithm.Padding = PaddingMode.PKCS7; PasswordDeriveBytes passwordDeriveBytes = new PasswordDeriveBytes(pass, salt); // FIXME: We are using SHA1 hardcoded here, because for some reason CryptDeriveKey doesn't // like other hash algorithms. Also, it appears to not like Rijndael as a encryption algorithm. secretKey = passwordDeriveBytes.CryptDeriveKey(encryptAlgorithm, "SHA1", symmetricAlgorithm.KeySize, iv); encoding = Esapi.SecurityConfiguration().CharacterEncoding; // 13 is the code for DSA asymmetricKeyPair = new CspParameters(13); // The asymmetric key will be stored in the key container using the name ESAPI. asymmetricKeyPair.KeyContainerName = "ESAPI"; // Set up signing keypair using the master password and salt // FIXME: Enhance - make DSA configurable RandomNumberGenerator randomNumberGenerator = RNGCryptoServiceProvider.Create(randomAlgorithm); } catch (Exception e) { // can't throw this exception in initializer, but this will log it new EncryptionException("Encryption failure", "Error creating Encryptor", e); } }
public async Task ShouldNotReturnCorruptedFileContent(int size, string storage) { const string path = "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789abc"; byte[] originalFileData = new byte[size]; byte[] originalFileHash; byte[] storedFileData; byte[] storedFileHash; using (var rng = RNGCryptoServiceProvider.Create()) using (var sha1 = SHA1.Create()) { rng.GetBytes(originalFileData); originalFileHash = sha1.ComputeHash(originalFileData); } using (var filesStore = NewStore(requestedStorage: storage)) { using (var session = filesStore.OpenAsyncSession()) { session.RegisterUpload(path, new MemoryStream(originalFileData)); await session.SaveChangesAsync(); } using (var session = filesStore.OpenAsyncSession()) { var refMetadata = new Reference <RavenJObject>(); var stream = await session.DownloadAsync(path, refMetadata); storedFileData = await stream.ReadDataAsync(); Assert.Equal(originalFileData.Length, storedFileData.Length); using (var sha1 = SHA1.Create()) { storedFileHash = sha1.ComputeHash(storedFileData); } } Assert.Equal(ToHexString(originalFileHash), ToHexString(storedFileHash)); } }
public static Audience AddAudience(string name) { //Generating random string of 32 characters as an identifier for the audience (client id). var clientId = Guid.NewGuid().ToString("N"); //Generating 256 bit random key using the “RNGCryptoServiceProvider” class then base 64 URL encode it, //this key will be shared between the Authorization server and the Resource server only. var key = new byte[32]; RNGCryptoServiceProvider.Create().GetBytes(key); var base64Secret = TextEncodings.Base64Url.Encode(key); //Add the newly generated audience to the in-memory “AudiencesList”. var newAudience = new Audience { ClientId = clientId, Base64Secret = base64Secret, Name = name }; audienceList.TryAdd(clientId, newAudience); return(newAudience); }
private void Initialize() { byte[] randomNumber = new byte[32]; using (RandomNumberGenerator crypto = RNGCryptoServiceProvider.Create()) crypto.GetBytes(randomNumber); _authenticationToken = Convert.ToBase64String(randomNumber); ProcessStartInfo start = new ProcessStartInfo(_nodePath) { WorkingDirectory = Path.GetDirectoryName(_nodePath), WindowStyle = ProcessWindowStyle.Hidden, Arguments = string.Format(CultureInfo.InvariantCulture, @"tools\server\we-nodejs-server.js --port {0} --anti-forgery-token {1} --environment production --process-id {2}", _port, _authenticationToken, Process.GetCurrentProcess().Id), UseShellExecute = false, CreateNoWindow = true }; _process = Process.Start(start); }