using System;
namespace 算法
{
class Program
{
static void Main(string[] args)
{
// 已排序数组
var a = new[] { 1, 2, 4, 5, 7, 9, 23, 45, 67, 89 };
Console.WriteLine(BinarySearch(a,89));
Console.ReadLine();
}
/// <summary>
/// 二分查找
/// </summary>
/// <param name="x">数组</param>
/// <param name="find">要查找的值</param>
/// <returns></returns>
private static int BinarySearch(int[] x, int find)
{
int low = 0, high = x.Length - 1;
while (low <= high)
{
int mid = (low + high) / 2, cmp = x[mid].CompareTo(find);
if (cmp < 0)
{
low = mid + 1;
}
else if (cmp > 0)
{
high = mid - 1;
}
else
{
return mid;
}
}
return -(low + 1);
}
}
}
Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts
2013-01-27
二分查找
2012-08-09
使用PBKDF2算法保护密码
1、 加密:
使用PBKDF2算法保护密码
//密码文字
string password = "Mgen!";
//随机填充密码salt
byte[]
salt = new byte[20];
var rng = RandomNumberGenerator.Create();
rng.GetBytes(salt);
//默认以UTF8(无BOM)得到字节。把salt保存到数据库
var kd = new Rfc2898DeriveBytes(password,
salt);
//输出密钥1
Console.WriteLine(BitConverter.ToString(kd.GetBytes(10)));
//更换salt
rng.GetBytes(kd.Salt);
//输出密钥2
Console.WriteLine(BitConverter.ToString(kd.GetBytes(10)));
把salt保存到数据库
Per
user per salt => 相同密码加密后不同
登陆时取出用户的加密密码和盐,使用用户输入的密码和盐加密,和数据库中取出的密码比较
更改密码是不修改盐
2010-10-12
2010-07-22
C#中用DllImport调用非托管代码
基本用法:调用系统的messagebox(位于user32.dll中)
入口点用于标识函数在 DLL 中的位置。 在托管对象中,目标函数的原名或序号入口点将 标识跨越交互操作边界的函数。 此外,您可以将入口点映射到一个不同的名称,这实际上是将函数重命名。
以下列出了重命名 DLL 函数的可能原因:
using System; using System.Runtime.InteropServices; class Example { // Use DllImport to import the Win32 MessageBox function. [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type); static void Main() { // Call the MessageBox function using platform invoke. MessageBox(new IntPtr(0), "Hello World!", "Hello Dialog", 0); } }至少要制定要导入的dll名称,可选字段:
- CharSet:制定字符集
- EntryPoint:制定入口点
入口点用于标识函数在 DLL 中的位置。 在托管对象中,目标函数的原名或序号入口点将 标识跨越交互操作边界的函数。 此外,您可以将入口点映射到一个不同的名称,这实际上是将函数重命名。
以下列出了重命名 DLL 函数的可能原因:
- 避免使用区分大小写的 API 函数名
- 符合现行的命名标准
- 提供采用不同数据类型的函数(通过声明同一 DLL 函数的多个版本)
- 简化对包含 ANSI 和 Unicode 版本的 API 的使用
using System.Runtime.InteropServices;
public class Win32 {
[DllImport("user32.dll", EntryPoint="MessageBoxA")]
public static extern int MsgBox(int hWnd, String text, String caption,
uint type);
}
Subscribe to:
Posts (Atom)