SHA512 hash in Excel - excel

i have a code for generating SHA512 hash of a string in excel, but on some notebook, it runs into error thanks to a net framework related problem. I have came accross a solution recently; when I open the "Me" expression in the locals window, the code can run without any error.
Locals:
Is there any chance to insert an additional code which can expand the "Me" expression in locals when i start running my VBA code in excel?
Sub sha512_kodolas()
Sheets("a").Range("a1").Value = h512(Sheets("b").Range("c1").Value)
End Sub
Function h512(ByVal S As String) As String
'https://msdn.microsoft.com/en-us/library/system.security.cryptography.sha512managed.aspx
Static UTF8 As Object, SHA As Object
Dim Data, Temp, i As Long
If SHA Is Nothing Then
Set UTF8 = CreateObject("System.Text.UTF8Encoding")
Set SHA = CreateObject("System.Security.Cryptography.SHA512Managed")
End If
Data = SHA.ComputeHash_2(UTF8.GetBytes_4(S))
ReDim Temp(LBound(Data) To UBound(Data)) As String
For i = LBound(Data) To UBound(Data)
Temp(i) = Right$("0" & Hex(Data(i)), 2)
Next
h512 = Join(Temp, "")
End Function

could you try this code: https://github.com/krijnsent/crypto_vba -> download the excel and try the ComputeHash_C function? It's also carrying out the SHA512 encryption, but in a slightly different way from yours, so I'm curious to know if it also crashes?

I tried the suggestion from the author above and it works like a charm: "could you try this code: https://github.com/krijnsent/crypto_vba -> download the excel and try the ComputeHash_C function? It's also carrying out the SHA512 encryption, but in a slightly different way from yours, so I'm curious to know if it also crashes?".
Simply clone the Github project, copy the following functions into your Excel workbook:
Function ComputeHash_C(Meth As String, ByVal clearText As String, ByVal key As String, Optional OutType As String) As Variant
Function ConvToBase64String(vIn As Variant) As Variant
Function ConvToHexString(vIn As Variant) As Variant
Function Base64Decode(ByVal base64String)
Function Base64Encode(inData)
It works perfectly well! Thanks for sharing this code!

Using the Excel file from https://github.com/krijnsent/crypto_vba, it works for me if I use commas rather than semicolons in the formula: =ComputeHash_C("SHA512",A3,"","STRHEX"). This is just a small variation on what Luc Krolls has posted.

Related

Using Application.Run to evaluate Worksheet function passed as string

I have essentially a simple syntax question concering Application.Run. I want to write a bit of code where I pass a UDF a string coantaining the name of a worksheet function, e.g. 'iserror' or some other UDF returning boolean. The function will then be exectued for each cell within the passed range and do something depending on result.
However, I have not been able to work out the proper Syntax. Error Messages Change along with my Trials, but non are particularly helpfull. e.g.:
?hrCull(Range("Data!A1:B10"),"Worksheetfunction.iserror", False)
(Error message in German, I'll try my best to translate, but it probably won't 100% match the English Version):
Runtime error 1004:
The macro 'Worksheetfunction.iserror' can not be exectued. The macro may not be available in this worksheet or macros have been deactivated.
Of course, macros have not been deactivated, but it isn't really a macro anyway. Also tried without the leading 'Worksheetfunction', same error message.
In my code the call Looks like this:
Public Function hrCull(r As Range, func As String, Optional invert As Boolean = False) As Range
Dim c As Range
Dim selector As Boolean
...
selector = Application.Run(func, c)
...
end function
I omitted code not relevant.
So what is the proper Syntax?
Misc:
- I'm Aware that I can not assert that the passed function returns a boolean.
- Excel 2016 on Windows 7
A solution using CallByName:
selector = CallByName(Application.WorksheetFunction, "IsError", VbMethod, c)
Lose the WorksheetFunction. prefix, Evaluate doesn't like it as Evaluate is for worksheet functions.
In your function, use:
selector = Application.Evaluate(func & "(" & c.Address & ")")
To test, use:
Debug.Print hrCull(Range("A1"), "ISERROR")
I think you'd be better off declaring your own Enum and adding the functions that you want into this. Then execute them using built in syntax instead of trying to evaluate a string
Public Enum xlSheetFunction
xlIsError
End Enum
Public Function hrCull(r As Range, func As xlSheetFunction, Optional Invert As Boolean = False) As Range
Dim selector As Boolean
Select Case func
Case xlIsError
selector = WorksheetFunction.IsError(r)
End Select
Debug.Print selector
Set hrCull = r
End Function
Public Sub test()
Debug.Print hrCull(Range("A1"), xlIsError)
End Sub

Unable to create simple VBA function in Excel Macro and call it

I'm trying to create a macro that can collect data from an excel spreadsheet in the local active workbook and then create header file which I would later incorporate into my project. But for the life of me I must be missing something so DUMB that I can't create a working function that returns a string (which would construct a C++ structure) to the calling function. I've simplified the example code to is absolute bare minimum to isolate the problem but I still cannot figure out what I'm doing wrong. I'm not an expert at VBA but I know how to create code and I can't narrow down what VBA is unhappy about. I keep getting "compile error, syntax error." Please copy the following code into your module and see if compiles properly for you. If you know where I went wrong please let me know. Much Appreciated!!!
Sub CREATE_FACTORY_SETTING_HEADER()
Dim FS, TSsource
Set FS = CreateObject("Scripting.FileSystemObject")
Dim TSout
Set TSout = FS.Createtextfile("HeaderFile.h", True)
Dim fileHeading As String
fileHeading = "File Heading for Header file"
Dim fileBody As String
fileBody = "Some initial file body lines"
fileBody = fileBody & createStructBody
TSout.Write fileHeading & fileBody
TSout.Close
End Sub
Public Function createStructBody() As String
Dim structBody As String
structBody = "Hey I'm a struct body, but I can't be returned for some reason"
Return structBody
End Function
Both VBA and VBScript use 'assignment to function' (instead of 'return' or 'result of last statement') to return results from functions. So
Public Function createStructBody() As String
createStructBody = "Hey I'm a string and can be returned."
End Function

Excel UDF not appearing in drop down menu

I wrote a User Defined Fucntion in Excel. It works great with no issues. I even wrote a description for it under the object properties menu.
The problem is, my UDF never shows up in the Excel drop down menu that appears when I start to type a function. I want the user to be able to see my UDF, named removeNumbers, when they go into a cell and start to type out a function.
I would also like them to be able to see the description which I wrote, just like the standard Excel functions.
And finally, is there a way that I can provide a description for each argument which my function takes as input?
Here is the actual code, although I don't think it will be necessary to answer my questions.
Function removeNumbers(sInput As String, sChoice As Boolean) As String
Dim sSpecialChars As String
Dim i As Long
If (sChoice = True) Then 'if true is selected, will remove all number including 0
sSpecialChars = "0123456789" 'This is your list of characters to be removed
For i = 1 To Len(sSpecialChars)
sInput = Replace$(sInput, Mid$(sSpecialChars, i, 1), "")
Next
End If
If (sChoice = False) Then 'if false is selected, will remove all numbers excluding zero
sSpecialChars = "123456789" 'This is your list of characters to be removed
For i = 1 To Len(sSpecialChars)
sInput = Replace$(sInput, Mid$(sSpecialChars, i, 1), "")
Next
End If
removeNumbers = sInput
End Function
To make the function appear in the drop-down you must place it in a standard module rather than the worksheet code area.
Another poster has already covered the need for the code to be in a standard module. With regards the argument descriptions, you should look at the MacroOptions code in this answer - although it only works in Excel 2010 or later.
For Excel 2007 and earlier, the only solution I have seen is in an article by JK Pieterse. This involves using the ExecuteExcel4Macro and looks a bit complicated.

Excel VBA - Use an existing string in called sub

I'm pretty new to this so apologies in advance
I'm half way through a userform in Excel and I'm trying to cut some fat off my code by using Call - I have 12 buttons that all do the same thing, the only difference is that each buttons sub is dependant on the buttons caption. My problem is that I can't figure out a way to use a String I've already declared in the Buttons Sub, then use it in the called Sub. I know you can do it, but my googling skills have failed me :(
Please could someone show me how to do this? Hope that all makes sense...
Here is a very small snippet of my code, but you get the jist:
Public Sub CommandButton4_Click()
Dim Name As String
Name = CommandButton4.Caption
Call Sort1
End Sub`
And the other one (Also tried this as function for the sake of trial and error)
Public Sub Sort1(Name As String)
Label11.Caption = Name
Sheets(Name).Select
End Sub
What you're referring to is passing an argument to another subroutine or function. Let's say you want to use a function a lot of times to get the first letter of a string. A sample of this is:
Function LeftOne(StrSample As String) As String
LeftOne = Left(StrSample, 1)
End Function
The above function can be used inside another function or subroutine provided you meet its requirement: StrSample. By declaring StrSample As String in the arguments field of the function, you are basically requiring that any calls to this should require a string to be passed to it. Anything else would throw an error.
The full line LeftOne(StrSample As String) As String can be read as: "I am function LeftOne. Pass me a string and I'll return to you a string after doing something with it." Note that the name StrSample is an arbitrary name.
Anyway, calling the above is as simple as:
Sub MsgInABox()
Dim StrToFeed As String
StrToFeed = "BK201"
MsgBox LeftOne(StrToFeed) 'Returns B.
End Sub
In your example, if you want to pass Name to Sort1, your attempt is absolutely correct.
Let us know if this helps.
You hat to give your sort1 procedure the parameter name.
call sort1(name)
or
call sort1(CommandButton4.Caption)

Can I use DPAPI (or something like it) in VBA?

another in my beginnerish series of questions about VBA.
I am in the process of writing an Excel add-in in VBA, and the add-in uses a local configuration file.
This file needs to contain a password for a remote service.
Obviously, it is less than ideal to store this password as plaintext. But I am looking for an algorithm that can encode/decode text so it at least doesn't look like plaintext in the configuration file.
I came across a reference to Windows DPAPI but I'm not sure whether this is an appropriate solution for Excel VBA. I also am not sure how I can use this API from within VBA, as I've only found references to using it with .NET. Visual Studio is unavailable to this project.
So the 2-part question is this:
1) If it is possible to use DPAPI from within VBA, can I have an example of its use?
2) If it is not possible to use DPAPI in VBA, do you have any suggestions for how to store text in some encoded fashion that is reversible?
The solution must work in Excel 2003 and later, if it matters.
Thank you once again.
The solution must work in Excel 2003 and later, if it matters.
For Excel VBA, I suggest using the CAPICOM Library.
Download the file from here. Once it is installed, follow these instructions for registering the Dll.
32 bit OS
Copy the file Capicom.dll from the C:\Program Files\Microsoft CAPICOM 2.1.0.2 SDK\Lib to C:\Windows\System32
Next on Start Menu | Run , type this
Regsvr32 C:\Windows\System32\Capicom.dll
64 bit OS
Copy the file Capicom.dll from the C:\Program Files (x86)\Microsoft CAPICOM 2.1.0.2 SDK\Lib\X86 to C:\Windows\SysWOW64
Next on Start Menu | Run , type this
Regsvr32 C:\Windows\SysWOW64\Capicom.dll
Now we are set to use it in our VBA Project
Paste this code in a module
Option Explicit
Sub Sample()
Dim TextToEncrypt As String, EncryptedText As String
Dim TextToDeCrypt As String, DeCryptedText As String
Dim KeyToEncrypt As String
TextToEncrypt = "Hello World"
KeyToEncrypt = "JoshMagicWord"
EncryptedText = EncryptString(TextToEncrypt, KeyToEncrypt)
DeCryptedText = DecryptString(EncryptedText, KeyToEncrypt)
Debug.Print "The string " & TextToEncrypt & " after encryption looks like this"
Debug.Print "-----------------------------------------------------------------"
Debug.Print EncryptedText
Debug.Print "-----------------------------------------------------------------"
Debug.Print "The above string after decrypting looks like this"
Debug.Print "-----------------------------------------------------------------"
Debug.Print DeCryptedText
End Sub
Public Function EncryptString(strText As String, ky As String) As String
Dim Cap As Object
Dim cryptIt
Set Cap = CreateObject("CAPICOM.EncryptedData")
Cap.Algorithm = 3
Cap.SetSecret ky
Cap.Content = strText
EncryptString = Cap.Encrypt
End Function
Public Function DecryptString(strText As String, ky As String) As String
Dim Cap As Object
Dim cryptIt
Set Cap = CreateObject("CAPICOM.EncryptedData")
Cap.Algorithm = 3
Cap.SetSecret ky
Cap.Decrypt strText
DecryptString = Cap.Content
End Function
The function EncryptString encrypts the string and the function DecryptString decrypts the string. See snapshot of results when you run the above Sub Sample

Resources