- Перевод и кодировка
Function GetHash(ByVal txt$) As String Dim oUTF8, oMD5, abyt, i&, k&, hi&, lo&, chHi$, chLo$ Set oUTF8 = CreateObject("System.Text.UTF8Encoding") Set oMD5 = CreateObject("System.Security.Cryptography.MD5CryptoServiceProvider") abyt = oMD5.ComputeHash_2(oUTF8.GetBytes_4(txt$)) For i = 1 To LenB(abyt) k = AscB(MidB(abyt, i, 1)) lo = k Mod 16: hi = (k - lo) / 16 If hi > 9 Then chHi = Chr(Asc("a") + hi - 10) Else chHi = Chr(Asc("0") + hi) If lo > 9 Then chLo = Chr(Asc("a") + lo - 10) Else chLo = Chr(Asc("0") + lo) GetHash = GetHash & chHi & chLo Next Set oUTF8 = Nothing: Set oMD5 = Nothing End Function
Sub Получение_MD5_HASH() txt = "текстовая строка" res = GetHash(txt) Debug.Print res End Sub
А во вложенном файле, — другой вариант кода для получения MD5 хэша, только уже без использования .Net Framework
(то есть будет работать на любом компьютере)
Ещё один вариант этой функции, — для получения хеша файла:
Function GetFileHash(ByVal path As String) As String On Error Resume Next Dim oUTF8, oMD5, abyt, i&, k&, hi&, lo&, chHi$, chLo$, GetBytes() As Byte, cnt& With CreateObject("Adodb.Stream") .Type = 1 ' adTypeBinary .Open .LoadFromFile path .Position = 0 GetBytes = .Read .Close End With cnt& = 0: cnt& = UBound(GetBytes) If cnt& = 0 Then Exit Function Set oMD5 = CreateObject("System.Security.Cryptography.MD5CryptoServiceProvider") abyt = oMD5.ComputeHash_2(GetBytes) For i = 1 To LenB(abyt) k = AscB(MidB(abyt, i, 1)) lo = k Mod 16: hi = (k - lo) / 16 If hi > 9 Then chHi = Chr(Asc("a") + hi - 10) Else chHi = Chr(Asc("0") + hi) If lo > 9 Then chLo = Chr(Asc("a") + lo - 10) Else chLo = Chr(Asc("0") + lo) GetFileHash = GetFileHash & chHi & chLo Next Set oUTF8 = Nothing: Set oMD5 = Nothing End Function
- 24308 просмотров
Не получается применить макрос? Не удаётся изменить код под свои нужды?
Оформите заказ у нас на сайте, не забыв прикрепить примеры файлов, и описать, что и как должно работать.
I would like to convert a number of excel cells in my document from a serial number to the MD5 hash of that serial number. Is there a precompiled formula in excel that does that, or is my only option to do VBA. If VBA, how would I do it?
asked Aug 17, 2010 at 0:01
2
I see that this question is old, but I needed something similar and though I could share how I solved the problem.
Create a Module and insert this code:
Function stringToUTFBytes(aString)
Dim UTF8
Set UTF8 = CreateObject("System.Text.UTF8Encoding")
stringToUTFBytes = UTF8.GetBytes_4(aString)
End Function
Function md5hashBytes(aBytes)
Dim MD5
Set MD5 = CreateObject("System.Security.Cryptography.MD5CryptoServiceProvider")
md5hashBytes = MD5.ComputeHash_2((aBytes))
End Function
Function bytesToHex(aBytes)
Dim hexStr, x
For x = 1 To LenB(aBytes)
hexStr = Hex(AscB(MidB((aBytes), x, 1)))
If Len(hexStr) = 1 Then hexStr = "0" & hexStr
bytesToHex = bytesToHex & hexStr
Next
End Function
To call MD5, you can use:
bytesToHex(md5hashBytes(stringToUTFBytes("change here")))
answered Jun 2, 2021 at 20:15
Доброй ночи, Павел! Это я в шутку процитировал.
Да, здесь точно не было, я бы заметил
Для Cuper: по ссылке в архиве есть файл MD5.dll, если его подключить через Tools-References , то:
‘ Нужно подключить библиотеку: Tools — References — MD5.dll
Function Hash(txt As String, Optional UpperCase = 0)
With New GetHash
Hash = .MD5(txt, UpperCase)
End With
End Function
Sub Test()
MsgBox Hash(«123»)
End Sub
Вместо подключения MD5.dll через references можно импортировать в проект файл MD5.cls
А если требуется обрабатывать много значений, то так будет быстрее:
‘ Нужно подключить библиотеку: Tools — References — MD5.dll
Dim oHash As New GetHash
Function Hash(txt As String, Optional UpperCase = 0)
Hash = oHash.MD5(txt, UpperCase)
End Function
Sub Test()
MsgBox Hash(«123»)
End Sub
Я не очень забочусь о столкновениях, но мне нужен слабый псевдорандомайзер
строки, основанные на строковом поле переменной длины. Вот одно безумное решение, которое хорошо работает:
=MOD(MOD(MOD(MOD(MOD(IF(LEN(Z2)>=1,CODE(MID(Z2,1,1))+10,31),1009)*IF(LEN(Z2)>=3,CODE(MID(Z2,3,1))+10,41),1009)*IF(LEN(Z2)>=5,CODE(MID(Z2,5,1))+10,59),1009)*IF(LEN(Z2)>=7,CODE(MID(Z2,7,1))+10,26),1009)*IF(LEN(Z2)>=9,CODE(MID(Z2,9,1))+10,53),1009)
здесь Z2
— это ячейка, содержащая строку, которую вы хотите хэш.
«MOD» S там предотвратить переполнить к научной нотации. 1009
является простым, может использовать что-нибудь X, так что X*255 < max_int_size
. 10 произвольно; используйте что угодно. Значения «Else» являются произвольными (цифры pi сюда!); используйте что угодно. Расположение символов (1,3,5,7,9) произвольное; используйте что угодно.
When capturing PII data (Personally identifiable information) in GA or Adobe analytics, you need to make sure that the values captured are encrypted/hashed to respect the rules of these platforms. Otherwise you might have your account deactivated without any prior notice! A very common hashing algorithm is MD5. It produces a 128-bit hash value and it’s a one-way hashing algorithm, meaning that you cannot convert the hashed value back to the original one. (Keep in mind that MD5 hashes are only secure when using a unique input value, to prevent reverse lookup attacks e.g. using https://md5.gromweb.com/ )
To be able to compare and correlated hashed values with offline data you need to also hash (using the same algorithm) the key value of your 2 data sets and then use the hashed values to connect them. Since excel is usually a very convenient tool for reporting and data manipulation below is a an Excel file showing how to get the MD5 hash value without using VBA, just plain Excel functions! This means that you don’t have to mess with additional source code and strange warnings in Excel, when opening the file.
This file is only available for Excel 2013 and above. Office 2013 comes with handy functions for bitwise operations like BITAND()
, BITOR()
, BITXOR()
, BITR[L]SHIFT()
. This file can process strings up to 1024 ASCII characters long. This is to reduce the file size (which is already 185 kb). If you need to process longer messages you can add calculation blocks to the bottom of the table (a single calculation block consists of 64 rows).
Credits to Taosique for creating this Excel file. Original post is here
Download
If you prefer using a single Excel function to generate an MD5 hash, you can use Phil Fresle’s VBA source code. By adding this as a class in your Excel file, you’ll be able to use the function “md5hash” to generate MD5 hashed values for any cell value.
Panagiotis (pronounced Panayotis) is a passionate G(r)eek with experience in digital analytics projects and website implementation. Fan of clear and effective processes, automation of tasks and problem-solving technical hacks. Hands-on experience with projects ranging from small to enterprise-level companies, starting from the communication with the customers and ending with the transformation of business requirements to the final deliverable.