public UserDisplay AuthenticateUser(string username, string password) { var user = _users.Get(u => u.Username.ToLower() == username.ToLower()); if (user == null) { throw new OverseerException("invalid_username"); } var passwordHash = PasswordHash.ScryptHashBinary(Encoding.UTF8.GetBytes(password), user.PasswordSalt); if (!user.PasswordHash.SequenceEqual(passwordHash)) { throw new OverseerException("invalid_password"); } if (!string.IsNullOrWhiteSpace(user.Token) && AuthenticateToken(user.Token) != null) { return(user.ToDisplay(includeToken: true)); } user.Token = Convert.ToBase64String(SodiumCore.GetRandomBytes(16)); if (user.SessionLifetime.HasValue) { user.TokenExpiration = DateTime.UtcNow.AddDays(user.SessionLifetime.Value); } else { user.TokenExpiration = null; } _users.Update(user); return(user.ToDisplay(includeToken: true)); }
private void GeneratePasswordButton_Click(object sender, RoutedEventArgs e) { string characters = ""; string password = ""; if (settings.GetUseLowercase() == true) { characters += "abcdefghijklmnopqrstuvwxyz"; } if (settings.GetUseUppercase() == true) { characters += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; } if (settings.GetUseNumbers() == true) { characters += "0123456789"; } if (settings.GetUseSpecialchars() == true) { characters += settings.GetAllowedSpecialchars(); } for (int i = 0; i < settings.GetDefaultPasswordlength(); i++) { int random = SodiumCore.GetRandomNumber(characters.Length); char c = characters[random]; password += c; } GeneratedPasswordTextbox.Text = password; }
/// <summary> /// Opens a pipe request with the other side of the tunnel. /// </summary> /// <param name="type"></param> /// <param name="id"></param> private PipeBase OpenPipe(PipeType type, UInt32 id = 0) { //the connecting party doesn't care about the pipe ID. if (id == 0) { id = BitConverter.ToUInt32(SodiumCore.GetRandomBytes(4), 0); } IHasSerializationTag c = new CreateAnonymousPipe(type.ToString(), id); PipeBase pipe = null; switch (type) { case PipeType.Control: throw new NotSupportedException( "Cannot create a new control pipe where on a tunnel that already has a control pipe"); case PipeType.Duplex: pipe = new DuplexPipe(this.mTunnel, id); break; default: throw new ArgumentOutOfRangeException("type"); } this.requestedPipes.Add(id, pipe); EncryptedPacket packet = new EncryptedPacket(this.mTunnel.ID, this.ID); packet.RPCs.Add(c); this.mTunnel.EncryptAndSendPacket(packet); return(pipe); }
public void SodiumVersionStringTest() { const string EXPECTED = "1.0.7"; var actual = SodiumCore.SodiumVersionString(); Assert.AreEqual(EXPECTED, actual); }
public static char[] GenerateRandomPassword(int length, bool lowercase, bool uppercase, bool numbers, bool symbols) { const string lowercaseCharacters = "abcdefghijklmnopqrstuvwxyz"; const string uppercaseCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; const string numberCharacters = "1234567890"; const string symbolCharacters = "!#$%*?@+-=^"; List <char> password = new List <char>(); while (password.Count < length) { bool characterAdded = false; byte[] characterByte = SodiumCore.GetRandomBytes(1); char character = (char)characterByte[0]; if (lowercase == true) { CheckCharacter(lowercaseCharacters, character, ref password, ref characterAdded); } if (uppercase == true && characterAdded == false) { CheckCharacter(uppercaseCharacters, character, ref password, ref characterAdded); } if (numbers == true && characterAdded == false) { CheckCharacter(numberCharacters, character, ref password, ref characterAdded); } if (symbols == true && characterAdded == false) { CheckCharacter(symbolCharacters, character, ref password, ref characterAdded); } } return(password.ToArray()); }
/// <summary> /// Initialize the EncryptedFileFooter for encryption. /// </summary> /// <param name="nonceLength">The length of the footer nonces.</param> /// <param name="chunkNumber">The number of chunks in the file.</param> /// <param name="overallChunkLength">The overall length of the chunks.</param> /// <remarks>Used for encryption.</remarks> public EncryptedFileFooter(int nonceLength, int chunkNumber, long overallChunkLength) { this.FooterNonceLength = SodiumCore.GetRandomBytes(nonceLength); this.FooterNonceCount = SodiumCore.GetRandomBytes(nonceLength); this.ChunkCount = BitConverter.GetBytes(chunkNumber); this.OverallChunkLength = BitConverter.GetBytes(overallChunkLength); }
public static void EncryptionErasure(string filePath, BackgroundWorker bgwShredFiles) { try { string encryptedFilePath = AnonymousRename.GetAnonymousFileName(filePath); using (var ciphertext = new FileStream(encryptedFilePath, FileMode.Create, FileAccess.ReadWrite, FileShare.Read)) using (var plaintext = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.Read)) { byte[] fileBytes = FileHandling.GetBufferSize(plaintext); byte[] key = SodiumCore.GetRandomBytes(Constants.EncryptionKeySize); byte[] nonce = SodiumCore.GetRandomBytes(Constants.XChaChaNonceLength); StreamCiphers.Encrypt(plaintext, ciphertext, 0, fileBytes, nonce, key, bgwShredFiles); Utilities.ZeroArray(key); Utilities.ZeroArray(nonce); } // Overwrite the original file File.Copy(encryptedFilePath, filePath, true); ShredFiles.EraseFileMetadata(encryptedFilePath); File.Delete(encryptedFilePath); } catch (Exception ex) when(ex is CryptographicException || ExceptionFilters.FileAccessExceptions(ex)) { Logging.LogException(ex.ToString(), Logging.Severity.High); DisplayMessage.ErrorResultsText(filePath, ex.GetType().Name, "'Encryption' erasure failed."); } }
public TunnelBase(TunnelSocket socket) { this._socket = socket; this.ID = Common.RemoveTIDFlags(BitConverter.ToUInt64(SodiumCore.GetRandomBytes(8), 0)); this.ActivePipes = new TreeDictionary <uint, PipeBase>(); this.congestionController = new NoCongestionControl(_socket, 250, 500, 1, 500); }
private static Route GenerateRoute(IList <NodeInfo> possibleNodes, int startSequenceId = 0, Route oldRoute = null) { var nodes = new RouteNode[3]; var i = 0; while (i < nodes.Length) { var nodeIndex = SodiumCore.GetRandomNumber(possibleNodes.Count); var node = possibleNodes[nodeIndex]; if (nodes.Any(n => n != null && n.Node.Id == node.Id)) { continue; } var keyPair = PublicKeyBox.GenerateKeyPair(); nodes[i++] = new RouteNode { EphemeralPublicKey = keyPair.PublicKey, SymmetricKey = GenerateSymmetricKey(node.PublicKey, null, keyPair.PublicKey, keyPair.PrivateKey), Node = node }; } return(new Route { StartSequenceId = startSequenceId, OldRoute = oldRoute, Nodes = nodes }); }
public void GenerateBytesTest() { var actual = SodiumCore.GetRandomBytes(24); //need a better test Assert.IsNotNull(actual); }
public void GenerateKeyVerifySignedDataTest() { var actual = PublicKeyAuth.GenerateKeyPair(); byte[] randomArray = SodiumCore.GetRandomBytes(255); var sign = PublicKeyAuth.SignDetached(randomArray, actual.PrivateKey); Assert.IsTrue(PublicKeyAuth.VerifyDetached(sign, randomArray, actual.PublicKey)); }
/// <summary> /// Creates a QuickPass from the given <paramref name="password"/> and /// <paramref name="imk"/> using the QuickPass settings stored in /// <paramref name="identity"/>, stores it in memory and establishes a /// timer that will clear the QuickPass after the timeout set forth in /// <paramref name="identity"/>'s QuickPass settings. /// </summary> /// <param name="password">The full identity master password.</param> /// <param name="imk">The identity's unencrypted Identity Master Key (IMK).</param> /// <param name="ilk">The identity's unencrypted Identity Lock Key (ILK).</param> /// <param name="identity">The identity that the QuickPass should be set for.</param> /// <param name="progress">An object implementing the IProgress interface for tracking the operation's progress (optional).</param> /// <param name="progressText">A string representing a text descrition for the progress indicator (optional).</param> public async void SetQuickPass(string password, byte[] imk, byte[] ilk, SQRLIdentity identity, IProgress <KeyValuePair <int, string> > progress = null, string progressText = null) { if (string.IsNullOrEmpty(password)) { Log.Warning("Can't use QuickPass on an empty password, aborting SetQuickPass()!"); return; } QuickPassItem qpi = new QuickPassItem() { EstablishedDate = DateTime.Now, QuickPassLength = identity.Block1.HintLength, IdentityUniqueId = identity.Block0.UniqueIdentifier.ToHex(), ScryptRandomSalt = SodiumCore.GetRandomBytes(16), Nonce = SodiumCore.GetRandomBytes(24), QuickPassTimeoutSecs = identity.Block1.PwdTimeoutMins * 60, ClearQuickPassOnIdle = identity.Block1.OptionFlags.ClearQuickPassOnIdle, ClearQuickPassOnSleep = identity.Block1.OptionFlags.ClearQuickPassOnSleep, ClearQuickPassOnSwitchingUser = identity.Block1.OptionFlags.ClearQuickPassOnSwitchingUser, Timer = new Timer() }; qpi.Timer.Enabled = false; qpi.Timer.AutoReset = false; // Dont restart timer after calling elapsed qpi.Timer.Interval = QP_GENERAL_TIMEOUT_SEC; qpi.Timer.Elapsed += QuickPassTimerElapsed; string quickPass = password.Substring(0, qpi.QuickPassLength); var enScryptResult = await SQRL.EnScryptTime( quickPass, qpi.ScryptRandomSalt, (int)Math.Pow(2, 9), QP_KEYDERIV_SEC, progress, progressText); qpi.ScryptIterationCount = enScryptResult.IterationCount; qpi.EncryptedImk = StreamEncryption.Encrypt(imk, qpi.Nonce, enScryptResult.Key); qpi.EncryptedIlk = StreamEncryption.Encrypt(ilk, qpi.Nonce, enScryptResult.Key); // If we already have a QuickPass entry for this identity, remove it first if (HasQuickPass(qpi.IdentityUniqueId)) { ClearQuickPass(qpi.IdentityUniqueId, QuickPassClearReason.Unspecified); } // Now, add the QuickPass item to our list and start the timer lock (_dataSyncObj) { _quickPassItems.Add(qpi.IdentityUniqueId, qpi); qpi.Timer.Start(); } Log.Information("QuickPass set for identity {IdentityUniqueId}", qpi.IdentityUniqueId); }
public static string[] AESEncryption(string key, string plainText) { var nonce = SecretAead.GenerateNonce(); var encodedKey = Encoding.UTF8.GetBytes(key); var encodedData = SodiumCore.GetRandomBytes(SodiumCore.GetRandomNumber(1147483647)); var cipherText = SecretAead.Encrypt(Encoding.UTF8.GetBytes(plainText), nonce, encodedKey, encodedData); return(new[] { Encoding.UTF8.GetString(cipherText), Encoding.UTF8.GetString(nonce), Encoding.UTF8.GetString(encodedData) }); }
/// <summary> /// Initializes a new instance of the <see cref="Tunnel.SecureTunnel"/> class on the /// specified port. /// </summary> /// <param name="port">Port.</param> public SecureTunnel(short port) : base(TunnelRuntime.GetOrCreateTunnelSocket(port)) { State = TunnelState.Starting; State = TunnelState.Disconnected; this.TunnelSocket = base._socket; base._socket.RegisterTunnel(this); this.ControlPipe = new ControlPipe(this); mCurNonce = SodiumCore.GetRandomBytes(24); }
public static bool Verify(string storedHash, string inputPassword) { string sha384Hash = Stretch(inputPassword); SodiumCore.Init(); bool val = Sodium.PasswordHash.ScryptHashStringVerify(storedHash, sha384Hash); return(val); //lembrete de como usar ScryptHashStringVerify: bool val = PasswordHash.ScryptHashStringVerify("$7$F6....0....pxzMLQ.od/XkQ1Qpi5THmDuEfCFAXH749DNJWKdlDV4$iPxlyMga4/tTxtVi.UyCthzE9WakgXQ7j4PAhi3M050", "lBeapXL/JwcY3D+XeUYcYR72+59k+Y8uaVtwB6pMBfA+Bmy0Px+kkHSeDXxoESaZ"); }
public static TraceContext New() { var context = new TraceContext { TraceId = SodiumCore.GetRandomBytes(16), ParentId = SodiumCore.GetRandomBytes(8), Flags = TraceFlags.None }; return(context); }
public static byte[] Nonce() { if (Globals.EncryptionAlgorithm == (int)Cipher.XChaCha20 || Globals.EncryptionAlgorithm == (int)Cipher.XSalsa20) { return(SodiumCore.GetRandomBytes(Constants.XChaChaNonceLength)); } else { return(SodiumCore.GetRandomBytes(Constants.AesNonceLength)); } }
private static int[] GenerateLineNumbers(int wordlistLength, int wordCount) { int[] lineNumbers = new int[wordCount]; for (int i = 0; i < wordCount; i++) { byte[] randomBytes = SodiumCore.GetRandomBytes(4); uint max = BitConverter.ToUInt32(randomBytes, 0); lineNumbers[i] = (int)(wordlistLength * (max / (double)uint.MaxValue)); } return(lineNumbers); }
public BigInteger GenerateAValues(out byte[] state) { _a = BigInteger.Abs(new BigInteger(SodiumCore.GetRandomBytes(32))); // A = g^a _A = BigInteger.ModPow(_g, _a, _N); state = _a.ToByteArray(); return(_A); }
public SecureTunnel(TunnelSocket socket) : base(socket) { State = TunnelState.Starting; //random TID ID = Common.RemoveTIDFlags(BitConverter.ToUInt64(SodiumCore.GetRandomBytes(8), 0)); TunnelSocket = socket; State = TunnelState.Disconnected; this.ControlPipe = new ControlPipe(this); mCurNonce = SodiumCore.GetRandomBytes(24); }
private static List <string> GetRandomWords(string[] wordlist, int length) { var words = new List <string>(); var textInfo = CultureInfo.CurrentCulture.TextInfo; for (int i = 0; i < length; i++) { int randomLine = SodiumCore.GetRandomNumber(wordlist.Length); words.Add(textInfo.ToTitleCase(wordlist[randomLine])); } return(words); }
// Function to generate encryption key. public static void GenerateEncryptionKey(string masterPassword) { // Generate random 32 byte encryption key, 12 byte random nonce and 32 byte hash to use as key from master password. byte[] encryptionKey = SodiumCore.GetRandomBytes(32); byte[] nonce = SecretAeadAes.GenerateNonce(); byte[] key = GenericHash.Hash(masterPassword, (byte[])null, 32); // Encrypt encryption key with master password. byte[] encryptedKey = SecretAeadAes.Encrypt(encryptionKey, nonce, key); // Store bytes in base64 encoding. File.WriteAllText(PIMUX_KEY, Convert.ToBase64String(encryptedKey)); File.WriteAllText(PIMUX_KEY_NONCE, Convert.ToBase64String(nonce)); }
private static List <string> GetRandomWords(string[] wordlist, int length) { var words = new List <string>(); var textInfo = new CultureInfo("en-US", useUserOverride: false).TextInfo; for (int i = 0; i < length; i++) { int randomLine = SodiumCore.GetRandomNumber(wordlist.Length); words.Add(textInfo.ToTitleCase(wordlist[randomLine])); } return(words); }
/// <summary> /// GenerateGenericKey - Generate key based on libsodium methods /// </summary> /// <param name="bytes">bytes of key</param> /// <returns>return key</returns> public string GenerateGenericKey(int bytes = 64) { if (bytes == 64) { var key = GenericHash.GenerateKey(); return(key.EncodeByteArray()); } else { var key = SodiumCore.GetRandomBytes(bytes); return(key.EncodeByteArray()); } }
/// <summary> /// Sets the next TID /// </summary> internal override UInt64 NextTID() { mNextKeyPair = PublicKeyBox.GenerateKeyPair(); mNextTID = BitConverter.ToUInt64(SodiumCore.GetRandomBytes(8), 0); /*if (!_socket.RegisterTunnelRekey(this, mNextTID)) * { * NextTID(); * }*/ //var nTID = new NextTID(mNextTID); //SendData(nTID.Serialize(), 0); return(mNextTID); }
public void GetRandomBytesTest() { var v16 = SodiumCore.GetRandomBytes(16); var v32 = SodiumCore.GetRandomBytes(32); var v64 = SodiumCore.GetRandomBytes(64); Assert.IsNotNull(v16); Assert.IsNotNull(v32); Assert.IsNotNull(v64); Assert.AreEqual(16U, v16.Length); Assert.AreEqual(32U, v32.Length); Assert.AreEqual(64U, v64.Length); }
public void Decrypt() { var Message = Encoding.ASCII.GetBytes("Hello World"); var Key = SodiumCore.GetRandomBytes(32); var Nonce = SodiumCore.GetRandomBytes(24); var CipherText = SecretBox.Create(Message, Nonce, Key); var PlainText = SecretBox.Open(CipherText, Nonce, Key); Assert.AreEqual(Encoding.ASCII.GetString(Message), Encoding.ASCII.GetString(PlainText)); }
/// <summary> /// Generate a new random key. /// </summary> /// <returns>A random key.</returns> private static Key GenerateNewKey() { var keyPair = PublicKeyBox.GenerateKeyPair(); var key = new Key { KeyType = KeyType.Lageant, PrivateKey = keyPair.PrivateKey, PublicKey = keyPair.PublicKey, KeyId = SodiumCore.GetRandomBytes(8), KeySalt = PasswordHash.GenerateSalt(), KeyNonce = PublicKeyBox.GenerateNonce() }; return(key); }
public static void NextBytes(Span <byte> buffer, int count, RandomSource source) { switch (source) { case RandomSource.SodiumCore: SodiumCore.GetRandomBytes(buffer, count); break; case RandomSource.NSec: RandomGenerator.Default.GenerateBytes(buffer); break; default: throw new NotSupportedException(); } }
public static void Main(string[] args) { SodiumCore.Init(); /* * var port = 57121; * * var udpClient = new UdpClient(port); * var proxy = new SocksProxy(8080, () => new ToriSocksConnection(udpClient)); */ var proxy = new SocksProxy(8080, () => new BasicSocksConnection()); proxy.Listen(); Console.ReadLine(); }