在我写的 CAS统一登录认证(13): ldap 批量导入用户 一文中,没有解决程序产生ldap,sha密码问题,后来,找到,在php中的代码
public function ldap_sha($password)
{
$ldap_passwd = “{SHA}”.base64_encode(pack(“H*”, sha1($password)));
return $ldap_passwd;
}
但要每个密码另外调用php加密不方便,就改成了c#的,并做了个测试程序,产生的密码和ldap加密的结果是一样的
不多说,上完整代码:
测试界面:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="testldapsha1.aspx.cs" Inherits="thirdpartyproxy.testldapsha1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="ldapsha1加密"
onclick="Button1_Click" />
<br />
<br />
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</div>
</form>
</body>
</html>
处理后台程序:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Cryptography;
using System.Text;
namespace thirdpartyproxy
{
public partial class testldapsha1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
static byte[] Sha1(byte[] str)
{
SHA1 sha1 = new SHA1CryptoServiceProvider();
return sha1.ComputeHash(str);
}
static string Sha1(string str)
{
SHA1 sha1 = new SHA1CryptoServiceProvider();
ASCIIEncoding enc = new ASCIIEncoding();
byte[] tmp = enc.GetBytes(str);
byte[] dataHashed = sha1.ComputeHash(tmp);
string hash = BitConverter.ToString(dataHashed).Replace("-", "");
hash = Convert.ToBase64String(dataHashed);
return hash;
}
protected void Button1_Click(object sender, EventArgs e)
{
string pwd = TextBox1.Text.Trim();
Label1.Text = Sha1(pwd);
}
}
}
运行界面: