# slappasswd -h {md5} -s "secret"
{MD5}Xr4ilOzQ4PCOq3aQ0qbuaQ==java
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之分版本:app
//算法:將密碼通過 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; }