I want to convert a password which is stored in binary to normal ASCII form so that i can read it. I need a VBscript for that and script should also return this de-crypted password
Eg: Encrypted Binary password: 00110001 00110010 00110011 00110100
De-crypted Original password : 1234
I Tried this
'Binary contains the binary password
dim S
For I = 1 To LenB(Binary)
S = S & Chr(AscB(MidB(Binary, I, 1)))
Next
MSGBOX S
But the output is
0
How can achieve this. Please help!!
If you are dealing with a byte array, you must know the character encoding before you can convert it to string. Without that knowledge the bytes will be converted to the wrong characters.
The ADODB.Stream object can handle byte arrays. Here is a function that that does that:
Const adTypeBinary = 1
Const adTypeText = 2
Const adModeReadWrite = 3
Function BytesToString(bytes, charset)
With CreateObject("ADODB.Stream")
.Mode = adModeReadWrite
.Type = adTypeBinary
.Open
.Write bytes
.Position = 0
.Type = adTypeText
.Charset = charset
BytesToString = .ReadText
End With
End Function
And here is how to use it:
MsgBox BytesToString(binary, "Windows-1252")
For the sake of completeness, this is the reverse operation:
Function StringToBytes(str, charset)
With CreateObject("ADODB.Stream")
.Mode = adModeReadWrite
.Type = adTypeText
.Charset = charset
.Open
.WriteText str
.Position = 0
.Type = adTypeBinary
StringToBytes = .Read
End With
End Function
Since your input seems to be a string like "00110001 00110010 00110011 00110100", here is a function to convert that to a byte array, which you can then use with BytesToString() shown above:
Function BinaryStringToBytes(binaryStr)
Dim b, n, i, l
l = GetLocale
SetLocale 1031
With CreateObject("ADODB.Stream")
.Mode = adModeReadWrite
.Charset = "Windows-1252"
.Type = adTypeText
.Open
For Each b In Split(binaryStr, " ")
If Len(b) <> 8 Or Replace(Replace(b, "0", ""), "1", "") <> "" Then
' invalid procedure call or argument
Err.Raise 5, "BinaryStringToBytes", _
"Only stings of 8-blocks of 0s and 1s, " & _
"separated by a single space are accepted."
End If
n = 0
For i = 0 To 7
n = n + Mid(b, 8 - i, 1) * 2^i
Next
.WriteText Chr(n)
Next
.Position = 0
.Type = adTypeBinary
BinaryStringToBytes = .Read
End With
SetLocale l
End Function
Usage
Dim input, output
input = "00110001 00110010 00110011 00110100"
output = BytesToString(BinaryStringToBytes(input), "Windows-1252")
MsgBox output ' -> "1234"
And, more importantly, it can handle multi-byte encodings properly:
input = "00110001 00110010 00110011 00110100 11000011 10100100"
output = BytesToString(BinaryStringToBytes(input), "UTF-8")
MsgBox output ' -> "1234รค"
try this code ;)
the code :
function BinaryToString(bin)
dim next_char
dim result
dim i
dim ascii
For i = 1 To Len(bin) + 18 Step 8
next_char = Mid(bin, i, 8)
ascii = BinaryToLong(next_char)
result = result & Chr(ascii)
Next
BinaryToString=result
end function
Function BinaryToLong(binary_value)
Dim hex_result
Dim nibble_num
Dim nibble_value
Dim factor
Dim bit
binary_value = UCase(Trim(binary_value))
If Left(binary_value, 2) = "&B" Then
binary_value = Mid(binary_value, 3)
End If
binary_value = Replace(binary_value, " ", "")
binary_value = Right(String(32, "0") & binary_value, 32)
For nibble_num = 7 To 0 Step -1
factor = 1
nibble_value = 0
For bit = 3 To 0 Step -1
If Mid(binary_value,1 + nibble_num * 4 + bit, 1) = "1" Then
nibble_value = nibble_value + factor
End If
factor = factor * 2
Next 'bit
hex_result = Hex(nibble_value) & hex_result
Next 'nibble_num
BinaryToLong = CLng("&H" & hex_result)
End Function
usage:
response.Write(BinaryToString("00110001001100100011001100110100"))
don't forget to take off " " blank spaces from the binary string
If I'm right, all you're after is converting a binary number to decimal (eg 0100 -> 4)?
dim binary, n, s
binary= "00110001"
For s = 1 To Len(binary)
n = n + (Mid(binary, Len(binary) - s + 1, 1) * (2 ^ (s - 1)))
Next 's
WScript.Echo binary & " = " & n
outputs
00110001 = 49
Converted from here: http://www.vb-helper.com/howto_decimal_to_binary.html
There are so many ways.
If it's a binary reg value then from Help (you did read it, didn't you)
The RegRead method returns values of the following five types.
Type Description In the Form of
REG_SZ
A string
A string
REG_DWORD
A number
An integer
REG_BINARY
A binary value
A VBArray of integers
REG_EXPAND_SZ
An expandable string (e.g., "%windir%\\calc.exe")
A string
REG_MULTI_SZ
An array of strings
A VBArray of strings
If a string, split on space (gives you an array of strings). The least significant bit is 2^0, 2^1, ..., 2^7.
EDIT
The normal way, not the only way though, to store a password, is to dump it in the registry.
Reading it gives you an array, not a scalar variable. So ...
The second method, handles cases where it's stored in a file.
Related
I am using vb6 and trying to generate a random number or String with this format
S1 = "378125649"
I have three requirements NO Duplicates Values & No Zeros & 9 charcters in length
I have approached This two very different ways the random number generator method is failing the FindAndReplace works but is too much code
The questions are
How to fix the GetNumber method code to meet the three requirement?
OR
How to simplify the FindAndReplace code to reflect a completely new sequence of numbers each time?
GetNumber code Below
Private Sub GetNumber()
Randomize
Dim MyRandomNumber As Long 'The chosen number
Dim RandomMax As Long 'top end of range to pick from
Dim RandomMin As Long 'low end of range to pick from
'Dim Kount As Long 'loop to pick ten random numbers
RandomMin = 1
RandomMax = 999999999
MyRandomNumber = Int(Rnd(1) * RandomMax) + RandomMin
lbOne.AddItem CStr(MyRandomNumber) & vbNewLine
End Sub
The FindAndReplace Code Below
Private Sub FindAndReplace()
Dim S4 As String
S4 = "183657429"
Dim T1 As String
Dim T2 As String
Dim J As Integer
Dim H As Integer
J = InStr(1, S4, 2)
H = InStr(1, S4, 8)
T1 = Replace(S4, CStr(J), "X")
T1 = Replace(T1, CStr(H), "F")
If Mid(T1, 8, 1) = "F" And Mid(T1, 2, 1) = "X" Then
T2 = Replace(T1, "F", "8")
T2 = Replace(T2, "X", "2")
End If
tbOne.Text = CStr(J) & " " & CStr(H)
lbOne.AddItem "Original Value " & S4 & vbNewLine
lbOne.AddItem "New Value " & T2 & vbNewLine
End Sub
Here's a way of generating 9-digit random numbers with no zeroes. The basic idea is to build a 9-character string position by position where each position is a random number between 1 and 9. Then each string is added to a collection to remove any duplicates. This code will generate 100,000 unique numbers:
Option Explicit
Private Sub Command1_Click()
Dim c As Collection
Set c = GetNumbers()
MsgBox c.Count
End Sub
Private Function GetNumbers() As Collection
On Error Resume Next
Dim i As Integer
Dim n As String
Randomize
Set GetNumbers = New Collection
Do While GetNumbers.Count < 100000
n = ""
For i = 1 To 9
n = n & Int((9 * Rnd) + 1)
Next
GetNumbers.Add n, n
Loop
End Function
In my testing, this code only generated 2 duplicates for the 100,000 unique numbers returned.
I don't have a VB6 compiler, so I winged it:
Function GetNumber(lowerLimit as Integer, upperLimit As Integer) As Integer
Dim randomNumber As String
Dim numbers As New Collection
Randomize
For i As Integer = lowerLimit To upperLimit
Call numbers.Add(i)
Next
For j As Integer = upperLimit To lowerLimit Step -1
Dim position As Short = Int(((j - lowerLimit)* Rnd) + 1)
randomNumber = randomNumber & numbers(position)
Call numbers.Remove(position)
Next
Return(CInt(randomNumber))
End Function
Use that function by calling for example:
GetNumber(1, 9)
I don't have VB6 on my machines anymore, so here's a solution written in Excel that shuffles the digits in 123456789 using an array.
You should be able to use it with little conversion:
Private Function RndNumber() As String
Dim i, j As Integer
Dim tmp As Variant
Dim digits As Variant
digits = Array("1", "2", "3", "4", "5", "6", "7", "8", "9")
For i = 0 To UBound(digits)
j = Int(9 * Rnd)
tmp = digits(i)
digits(i) = digits(j)
digits(j) = tmp
Next
RndNumber = Join(digits, "")
End Function
Here's a variation to play with that will shuffle an array you pass in and join them together with the specified separator. Note that the arrays being passed in are of variant type so anything can be shuffled. The first array has numbers while the second array has strings:
Private Sub Foo()
Dim digits As Variant
digits = Array(1, 2, 3, 4, 5, 6, 7, 8, 9)
Dim rndNnumber As String
RndNumber = ShuffleArrayAndJoin(digits, "")
Debug.Print RndNumber
Dim pets As Variant
pets = Array("cat", "dog", "fish", "hamster")
Dim rndPets As String
rndPets = ShuffleArrayAndJoin(pets, ", ")
Debug.Print (rndPets)
End Sub
Private Function ShuffleArrayAndJoin(ByVal sourceArray As Variant, ByVal separator As String) As String
Dim i, j As Integer
Dim tmp As Variant
For i = 0 To UBound(sourceArray)
j = Int(UBound(sourceArray) * Rnd)
tmp = sourceArray(i)
sourceArray(i) = sourceArray(j)
sourceArray(j) = tmp
Next
ShuffleArrayAndJoin = Join(sourceArray, separator)
End Function
Function GetNumber() As String
Dim mNum As String
Randomize Timer
Do While Len(mNum) <> 9
mNum = Replace(Str(Round(Rnd(Timer), 6)) + Str(Round(Rnd(Timer), 3)), " .", "")
Loop
GetNumber = mNum
End Function
Been clicking a button to load a text box for a couple of minutes, but so far no dupes, and I'd bet money there never will be any..
Well, it solves just 1 problem: it will never ever repeat number
but it has to be 15+ numbers long...
Function genRndNr(nrPlaces) 'must be more then 10
Dim prefix As String
Dim suffix As String
Dim pon As Integer
prefix = Right("0000000000" + CStr(DateDiff("s", "2020-01-01", Now)), 10)
suffix = Space(nrPlaces - 10)
For pon = 1 To Len(suffix)
Randomize
Randomize Rnd * 1000000
Mid(suffix, pon, 1) = CStr(Int(Rnd * 10))
Next
genRndNr = prefix + suffix
End Function
I have written code for an array of numbers which prints out. I'm now writing code to split the array into even and off numbers. I've started off with an if statement to separate the numbers but i'm struggling to find a solution on how to do it. My code below is failing as it's unable to split the numbers.
Sub main()
a=Array(5,10,15,20)
for each x in a
Msgbox(x)
If MyArray(I) / 2 = MyArray(I)
List1.AddItem MyArray(I) ' Even Integers
Else
List2.AddItem MyArray(I) ' Odd Integers
End if
next
End Sub
As Lankymart suggests, the simplest approach would be to use Mod() and check if the remainder is 1 or 0, but you can also do it with the approach you seemed to be working towards:
If MyArray(index)/2 = Int(MyArray(index)/2) Then
' Even number
Else
' Odd number
End If
Mod() approach:
If MyArray(index) Mod 2 = 0 Then
' Even number
Else
' Odd number
End If
Here's a complete subroutine that demonstrates what you are trying to do:
Dim arr(4) As Integer
Dim arrEven() As Integer
Dim iEvenValues As Integer
Dim arrOdd() As Integer
Dim iOddValues As Integer
Dim iCounter As Integer
' Initialize array
arr(0) = 5
arr(1) = 10
arr(2) = 15
arr(3) = 20
For iCounter = 1 To UBound(arr)
If arr(iCounter - 1) Mod 2 = 0 Then
iEvenValues = iEvenValues + 1
ReDim Preserve arrEven(iEvenValues)
arrEven(iEvenValues - 1) = arr(iCounter - 1)
Else
iOddValues = iOddValues + 1
ReDim Preserve arrOdd(iOddValues)
arrOdd(iOddValues - 1) = arr(iCounter - 1)
End If
Next
Dim sValues As String
sValues = "Even values (" & iEvenValues & "):"
For iCounter = 1 To UBound(arrEven)
sValues = sValues & " " & arrEven(iCounter - 1)
Next
MsgBox sValues
sValues = "Odd values (" & iOddValues & "):"
For iCounter = 1 To UBound(arrOdd)
sValues = sValues & " " & arrOdd(iCounter - 1)
Next
MsgBox sValues
I have a script as a counter subscribing to the file C:\tmp\yourtextfile.txt:
Set myFSO = CreateObject ("Scripting.FileSystemObject")
Licznik_ID = myFSO.OpenTextFile ("C:\tmp\yourtextfile.txt"). ReadAll
Licznik_ID + 1 = Licznik_ID
myFSO.OpenTextFile ( "C:\tmp\yourtextfile.txt", 2, True) .write (Licznik_ID)
how to do that instead of counting the counter in such a way:
1
2
3
4
5
6
7
8
9
10
11
e.t.c.
the Counter in the following way to read and save the file to C:\tmp\yourtextfile.txt?
00000001
00000002
00000003
00000004
00000005
00000006
00000007
00000008
00000009
00000010
00000011
e.t.c.
You need to first read the text, get the last part with split, convert it to a number, add 1, concatanate that that tot the string and write to the file.
Here your adapted script
Function PadZeros(s, l)
PadZeros = Right("00000000" & s, l)
End Function
Dim myFSO, Licznik_ID, txt, arr
Set myFSO = CreateObject ("Scripting.FileSystemObject")
txt = myFSO.OpenTextFile ("C:\tmp\yourtextfile.txt").ReadAll
arr = split(txt, " ")
Licznik_ID = arr(UBound(arr))
txt = txt & " " & PadZeros(CInt(Licznik_ID)+1, 8)
myFSO.OpenTextFile ("C:\tmp\yourtextfile.txt", 2, True).write (txt)
As an extra: since I'm switched to Ruby here the equivalent in that language to show you the power of Ruby
filename = "C:/tmp/yourtextfile.txt"
txt = File.read(filename)
txt += " %08d" % ((txt.split.last.to_i)+1).to_s
File.write(filename, txt)
or as a single line
File.read(filename).tap {|txt| File.write(filename, txt + " %08d" % ((txt.split.last.to_i)+1))}
It's pretty much explaining itself, the %08d is a formatting template for the string which takes the number and adds until 8 leading zero's, the tap method enumerates the object, in this case the last line of the file
First of all, have you tested this code? because it shouldn't work..
You should replace this line Licznik_ID + 1 = Licznik_ID with Licznik_ID = Licznik_ID + 1.
Now, in order to pad the number with leading zeros in vbscript, you'll have to write a function for that. You can use the following code:
Function LPad(str, l)
Dim n : n = 0
If l > Len(str) Then n = l - Len(str)
LPad = String(n, "0") & str
End Function
Set myFSO = CreateObject ("Scripting.FileSystemObject")
Licznik_ID = myFSO.OpenTextFile ("C:\tmp\yourtextfile.txt").ReadAll
Licznik_ID = Licznik_ID + 1
myFSO.OpenTextFile("C:\tmp\yourtextfile.txt", 2, True).write(LPad(Licznik_ID, 8))
Where LPad(Licznik_ID, 8) adds leading zeros to your number to produce an eight digit number. You can replace 8 with the preferred digit numbers.
Hope that helps :)
I have below sample data. I want to convert this string into an array
device_name="Text Data" d_id=7454579598 status="Active" Key=947-4378-43248274
I tried below:
Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile _
("d:\vbfile.txt", ForReading)
Do Until objTextFile.AtEndOfStream
strNextLine = objTextFile.Readline
arrServiceList = Split(strNextLine , " ")
For i = 0 to Ubound(arrServiceList)
Wscript.Echo arrServiceList(i)
Next
Loop
it generates below
device_name="Text
Data"
d_id=7454579598
status="Active"
Key=947-4378-43248274
Expected output
device_name="Text Data"
d_id=7454579598
status="Active"
Key=947-4378-43248274
How about this approach:
Option Explicit
Const ForReading = 1
Dim FSO, keyValueExpr
Set FSO = CreateObject("Scripting.FileSystemObject")
Set keyValueExpr = New RegExp
keyValueExpr.Pattern = "\b(\w+)=(""[^""]*""|\S*)"
keyValueExpr.Global = True
Dim result, record, match
Set result = CreateObject("Scripting.Dictionary")
With FSO.OpenTextFile("D:\vbfile.txt", ForReading)
While Not .AtEndOfStream
Set record = CreateObject("Scripting.Dictionary")
result.Add result.Count + 1, record
For Each match In keyValueExpr.Execute(.ReadLine)
record.Add match.SubMatches(0), match.SubMatches(1)
Next
Wend
.Close
End With
Dim msg, lineNo, key
For Each lineNo In result
msg = "Line " & lineNo & vbNewLine
For Each key In result(lineNo)
msg = msg & vbNewLine & key & ": " & result(lineNo)(key)
Next
MsgBox msg
Next
It uses a regular expression that can identify key-value pairs that fulfill these conditions:
The key is a string of characters (a-z), digits (0-9) or underscores (_)
The value is anything that is either enclosed in double quotes or anything except a space.
Compare https://regex101.com/r/zL2mX5/1
The program creates nested dictionaries, the outer dictionary holding all lines of the file with the corresponding line numbers (1..n) for keys, each inner dictionary holds the key-value pairs found on each line.
This layout gives you the opportunity to address every value very conveniently:
value = result(3)("status")
Here is a function that might help. It takes a string and a delimiter and returns an array obtained by splitting on the delimiter -- whenever the delimiter isn't inside a quote:
Function SmartSplit(s, d)
Dim c, i, j, k, n, A, quoted
n = Len(s)
ReDim A(n - 1)
quoted = False
i = 1
k = 0
For j = 1 To n
c = Mid(s, j, 1)
If c = """" Then quoted = Not quoted
If c = d And Not quoted Then
A(k) = Mid(s, i, j - i)
k = k + 1
i = j + 1
End If
Next
If i < n Then
A(k) = Mid(s, i)
Else
k = k - 1
End If
ReDim Preserve A(k)
SmartSplit = A
End Function
In your example -- just replace Split by SmartSplit and it should work.
I need to create multi-dimensional array of strings. Each row of the array can have varying number of strings. Something like the follwing code:
twoDimension = Array(Array())
ReDim Preserve twoDimension(3)
For i = 0 to 2
If i = 1 Then
twoDimension(i) = Array(1,2,3)
End If
If i = 2Then
twoDimension(i) = Array(1,2,3,4,5)
End If
Next
How about a dictionary
Set a = CreateObject("Scripting.Dictionary")
a.Add 0, Array(1,2,3)
a.Add 1, Array(4,5,6)
MsgBox a.Count
MsgBox a.Item(0)(2)
MsgBox a.Item(1)(1)
There's nothing wrong with having jagged arrays in VBScript. There are some minor issues with your code (ReDim to 3 but only assigning values to 2, unnecessarily using a For loop to assign values), but in general, that's the correct syntax to use.
Option Explicit
Dim twoDimension, i, j
twoDimension = Array(Array())
ReDim Preserve twoDimension(2)
twoDimension(1) = Array(1,2,3)
twoDimension(2) = Array(1,2,3,4,5)
For i = 0 To UBound(twoDimension)
For j = 0 To UBound(twoDimension(i))
WScript.Echo "(" & i & "," & j & ") = " & twoDimension(i)(j)
Next
Next