OpenLdap的加密md5(Java+Python,同时提供明文-->密文,md5(名文)-->密文两种方法)...

# slappasswd -h {md5} -s "secret"
{MD5}Xr4ilOzQ4PCOq3aQ0qbuaQ==

import base64
import hashlib
import passlib.hash
import binascii

# 测试用例
sourceString = '123456'
#=====================================================================================
# 分解动作版
# md5加密串
md5String=hashlib.md5(sourceString.encode('utf-8')).hexdigest()
# ascii码加密串
binasciiString = binascii.a2b_hex(md5String)
# base64加密串
base64String = base64.b64encode(binasciiString).decode('utf=8')
# 测试用例
print("{MD5}" + base64String)
# ====================================================================================
# ldap一步到位版本
def hash_md5(data):
    md = hashlib.md5()
    md.update(str(data))
    a = md.digest()
    b = base64.b64encode(a)
    return b
print(passlib.hash.ldap_md5.encrypt(sourceString))
# ====================================================================================

 

 

Java之一步到位版本:

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import sun.misc.BASE64Encoder;

public class SimpleMD5Example {

      public static String EncoderByMd5(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException{
            MessageDigest md5=MessageDigest.getInstance("MD5");
            BASE64Encoder base64en = new BASE64Encoder();
            String newstr=base64en.encode(md5.digest(str.getBytes("utf-8")));
            return newstr;
        }
      
    public static void main(String[] args) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        /*
        slappasswd -h {md5} -s "secret"
        {MD5}Xr4ilOzQ4PCOq3aQ0qbuaQ==
        */
        String passwordToHash = "secret";
        String N_md5=EncoderByMd5(passwordToHash);
        System.out.println(N_md5);
        
        
        /*
        slappasswd -h {md5} -s "dsideal4r5t6y7u"
        {MD5}yDL5JsEkVI9aVYfIW1pbPw==
        */
        passwordToHash = "dsideal4r5t6y7u";
        N_md5=EncoderByMd5(passwordToHash);
        System.out.println(N_md5);
    }
}

 Java之分版本:

//算法:将密码经过 MD5 运算,得到 32 字节的字符串,然后每2个字节压缩成一个十六进制字符,这样得到16字节的字符串,最后经过Base64编码。
        public static String getLdapPassword(String md5pass)
        {
            BASE64Encoder base64en = new BASE64Encoder();        
            byte[] baKeyword = new byte[md5pass.length() / 2];
            for (int i = 0; i < baKeyword.length; i++) {
                try {
                    baKeyword[i] = (byte) (0xff & Integer.parseInt(md5pass.substring(i * 2, i * 2 + 2), 16));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            String newstr = base64en.encode(baKeyword);        
            return newstr;
        }

 

你可能感兴趣的:(OpenLdap的加密md5(Java+Python,同时提供明文-->密文,md5(名文)-->密文两种方法)...)