1. 程式人生 > >CAS統一登入認證(18): ldap sha加密演算法

CAS統一登入認證(18): ldap sha加密演算法

在我寫的 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>
&nbsp;<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);
        }
    }
}

執行介面: