VB 2013: Auto login from my.settings issue - javascript

I am using the latest version of Awesomium for the WebControl for my application. When my application arrives at "accounts.google.com/ServiceLogin" it is supposed to execute some Javascript to have it automatically log in. In my.settings.java I have:
"document.getElementById('Email').value=""1"";document.getElementById('Passwd').value=""2"";document.getElementById('signIn').click()"
Value "1" being the email, and "2" being the password. So when the document is ready I have this:
Private Sub WebBrowser1_DocumentReady(sender As Object, e As Awesomium.Core.UrlEventArgs) Handles WebBrowser1.DocumentReady
If WebBrowser1.Source.ToString.Contains("accounts.google.com/ServiceLogin") = True Then
WebBrowser1.ExecuteJavascript(My.Settings.java.ToString)
Else
End If
I don't know why this is not working. When I paste the code directly in like this:
WebBrowser1.ExecuteJavascript("document.getElementById('Email').value=""1"";document.getElementById('Passwd').value=""2"";document.getElementById('signIn').click()")
The code works perfectly and it logs in. The reason I have it in my.settings is because I originally have it in a textbox, then I ask the user for their email and password, and then replace "1" with the email, and "2" with the password, then save the edited textbox text in my.settings.java. Then I have it look for the Javascript there instead of hard coding it into the application, and not being able to customize it for each user. Is any of my code wrong, or is there another way of doing this with Awesomium. Also, I am using the Awesomium WebControl1, I just changed it to WebBrowser1 because that is what I am used to typing. Sorry if this question is simple, as I am a student developer, with very limited knowledge in Javascript.

I never user my.settings when it comes to sensitive data like passwords (even emails). What I always do, I encrypt them in XML file using a simple yet dynamic encryption like this :
Public Function Encrypt(ByVal plainText As String) As String
Dim passPhrase As String = **My.Computer.Name.ToString**
Dim saltValue As String = **My.Computer.Info.OSFullName.ToString**
Dim hashAlgorithm As String = "SHA1"
Dim passwordIterations As Integer = 2
Dim initVector As String = "#1B2c3D4e5F6g7H8"
Dim keySize As Integer = 256
Dim initVectorBytes As Byte() = Encoding.ASCII.GetBytes(initVector)
Dim saltValueBytes As Byte() = Encoding.ASCII.GetBytes(saltValue)
Dim plainTextBytes As Byte() = Encoding.UTF8.GetBytes(plainText)
Dim password As New PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations)
Dim keyBytes As Byte() = password.GetBytes(keySize \ 8)
Dim symmetricKey As New RijndaelManaged()
symmetricKey.Mode = CipherMode.CBC
Dim encryptor As ICryptoTransform = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes)
Dim memoryStream As New IO.MemoryStream()
Dim cryptoStream As New CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length)
cryptoStream.FlushFinalBlock()
Dim cipherTextBytes As Byte() = memoryStream.ToArray()
memoryStream.Close()
cryptoStream.Close()
Dim cipherText As String = Convert.ToBase64String(cipherTextBytes)
Return cipherText
End Function
Public Function Decrypt(ByVal cipherText As String) As String
Dim passPhrase As String = **My.Computer.Name.ToString**
Dim saltValue As String = **My.Computer.Info.OSFullName.ToString**
Dim hashAlgorithm As String = "SHA1"
Dim passwordIterations As Integer = 2
Dim initVector As String = "#1B2c3D4e5F6g7H8"
Dim keySize As Integer = 256
Dim initVectorBytes As Byte() = Encoding.ASCII.GetBytes(initVector)
Dim saltValueBytes As Byte() = Encoding.ASCII.GetBytes(saltValue)
Dim cipherTextBytes As Byte() = Convert.FromBase64String(cipherText)
Dim password As New PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations)
Dim keyBytes As Byte() = password.GetBytes(keySize \ 8)
Dim symmetricKey As New RijndaelManaged()
symmetricKey.Mode = CipherMode.CBC
Dim decryptor As ICryptoTransform = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes)
Dim memoryStream As New IO.MemoryStream(cipherTextBytes)
Dim cryptoStream As New CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read)
Dim plainTextBytes As Byte() = New Byte(cipherTextBytes.Length - 1) {}
Dim decryptedByteCount As Integer = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length)
memoryStream.Close()
cryptoStream.Close()
Dim plainText As String = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount)
Return plainText
End Function
And it's still not that safe. The best way is to let the user put the password.
As for your answer , if I understand you question, you need to create profiles, and store them in files/registry. (I recommend files or database). So that when "John" uses your program, he will select the "John" profile ... and so on.

Related

Not able to decrypt the encryptedValue using crypto

I am trying to decrypt a value (encrypted in des) coming from VB.
When I try to decrypt the encryptedValue using crypto in Javascript the output gives me an empty value.
I have attached how the encryption was done in VB.
HOW I AM TRYING TO DECRYPT IN JAVASCRIPT
var CryptoJS = require("crypto-js");
var key = "peekaboo";
var encryptedValue = "50AznWWn4fJI19T392wIv/ZysP/Ke3mB";
encryptedValue = CryptoJS.enc.Base64.parse(encryptedValue);
var data = CryptoJS.DES.decrypt(encryptedValue, key, { iv: "cbauthiv" });
const email = data.toString(CryptoJS.enc.Utf8);
console.log(email, "ORIGINAL TEXT");
THE WAY IT IS ENCRYPTED IN VB
Imports System.Security.Cryptography
Imports System.Text
Imports System.IO
Module Module1
Private Const ENCRYPTIONKEY As String = "peekaboo"
Sub Main()
Dim s As String = Encrypt("ditzymoose#outlook.com")
Dim r As String = Decrypt(s)
Console.ReadLine()
End Sub
Private Function Encrypt(stringToEncrypt As String) As String
Dim rng As New RNGCryptoServiceProvider
Dim byteArray() As Byte = New Byte(8) {}
Dim iv_value As String = "cbauthiv"
Dim key() As Byte = {}
Dim IV() As Byte = System.Text.Encoding.UTF8.GetBytes(Left(iv_value, 8))
key = System.Text.Encoding.UTF8.GetBytes(Left(ENCRYPTIONKEY, 8))
Dim des As New DESCryptoServiceProvider
rng.GetBytes(byteArray)
Dim Salt As String = BitConverter.ToString(byteArray)
Dim SaltedInput As String = Salt & "~" & stringToEncrypt
Dim inputByteArray() As Byte = Encoding.UTF8.GetBytes(stringToEncrypt)
Dim ms As New MemoryStream
Dim cs As New CryptoStream(ms, des.CreateEncryptor(key, IV), CryptoStreamMode.Write)
cs.Write(inputByteArray, 0, inputByteArray.Length)
cs.FlushFinalBlock()
Return Convert.ToBase64String(ms.ToArray())
End Function
End Module
The key and IV must be passed as WordArray. For the conversion the Utf8-Encoder has to be used, here.
Also, the ciphertext must be passed as a CipherParams object or alternatively Base64 encoded (which is then implicitly converted to a CipherParams object), here.
With these changes the ciphertext of the VB code can be successfully decrypted using the CryptoJS code:
var key = CryptoJS.enc.Utf8.parse("peekaboo");
var iv = CryptoJS.enc.Utf8.parse("cbauthiv");
var encryptedValue = "50AznWWn4fJI19T392wIv/ZysP/Ke3mB";
var data = CryptoJS.DES.decrypt(encryptedValue, key, {iv: iv});
var email = data.toString(CryptoJS.enc.Utf8);
console.log(email, "ORIGINAL TEXT");
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.min.js"></script>
Please note that DES is insecure (here) and was replaced by AES almost 20 years ago. Also insecure is a static IV. Instead, a random IV should be generated for each encryption.
Furthermore a password should not be used as key. If a password is to be used, the key should be derived from the password using a reliable key derivation function such as PBKDF2.

Different HMAC for CryptoJS and VB

I have to generate a HMACSHA256 in Visual Basic. Problem is, that I didnt receive the correct HMAC and get different HMACS
InputData = Test\nTest\n\nTest
secret = c39ff802b43a01c08ea759750c41d7d4bac6b1b884b3864d640b577cf1dca21a
HMACa = 330c55857e5ff197a407a9dcd41bbf03a2e8de0b351aba9a405139919b3cae57
HMACb = f701ea7028f20df11a52bee297a336de212655a8bad01d848eeaa87d0f76ee5e
JS(CryptoJS) -> HMACa (Tested directly)
PY -> HMACa (Tested directly)
JS(jsSHA) -> HMACb (Tested under: liavaag.org/English/SHA-Generator/HMAC/)
C#/VB -> HMACb (Tested directly)
Why do i get different HMAC's and what can i do to get HMACa in VB/C#??
Here is my VB Code:
Sub Main()
Dim sToHash As String = "Test\nTest\n\nTest"
Dim sKey As String = "c39ff802b43a01c08ea759750c41d7d4bac6b1b884b3864d640b577cf1dca21a"
Console.WriteLine(getHMAC(sToHash, sKey))
End Sub
Function getHMAC(ToHash As String, SecretKey As String) As String
Dim aoText() As Byte = System.Text.Encoding.UTF8.GetBytes(ToHash)
Dim aoKey() As Byte = System.Text.Encoding.UTF8.GetBytes(SecretKey)
Using oHmac As New System.Security.Cryptography.HMACSHA256(aoKey)
Dim sHash As Byte() = oHmac.ComputeHash(aoText)
Return ByteToString(sHash)
End Using
End Function
Function ByteToString(buff As Byte()) As String
Dim getbinary As String = ""
For i As Integer = 0 To buff.Length - 1
getbinary += buff(i).ToString("X2")
Next
Return (getbinary).ToLower
End Function
It's a lot easier than intended. VB/C# can't Encode '\n' as NewLine. In World of VisualBasic you have to write vbLf to Indicate a NewLine in a String
So the correct InputString is now:
"Test" + vbLf + "Test" + vbLf + vbLf + "Test"
Result => HMACa
Thanks anyway

Downloading File from IE using VBA

I am currently working on a VBA code that retrieves the top file from this website (http://infopost.bwpmlp.com/Posting/default.aspx?Mode=Display&Id=27&tspid=100000). I am able to click on the button using Javascript in my code, and I am able to click on open after the download is kicked off. However, I am having trouble saving the file. Because the workbook is being pulled from a website there really isn't a way to set it to the active workbook that I can think of. Currently when I do ActiveWorkbook.SaveAs the code is saving the blank workbook that I am testing the code out of. The file I downloaded seems to not open until the entire code is done running even after I try putting in breaks. Anyone have any ideas? My code is below. Thanks!
Option Explicit
Dim ie As InternetExplorer
Dim h As LongPtr
Private Declare PtrSafe Function FindWindowEx Lib "user32" Alias "FindWindowExA" (ByVal hWnd1 As LongPtr, ByVal hWnd2 As LongPtr, ByVal lpsz1 As String, ByVal lpsz2 As String) As LongPtr
Sub Texas_Gas()
Application.DisplayAlerts = True
Dim ie As Object
Dim IeHandle As Long, FileDownloadHandle As Long, OpenButtonHandle As Long, IePopupBarHandle As Long
Dim AutoMode As Boolean, FileDownloadClassicPopup As Boolean, DownloadComplete As Boolean
Dim Timeout As Date
Dim strSPICE As String, strLink As String
Dim PopupGap As Integer, i As Integer
Set ie = CreateObject("InternetExplorer.Application")
DownloadComplete = False
FileDownloadClassicPopup = False
FileDownloadHandle = 0
IePopupBarHandle = 0
With ie
.Visible = True
.navigate "http://infopost.bwpmlp.com/Posting/default.aspx? Mode=Display&Id=27&tspid=100000"
Do While .Busy: DoEvents: Loop
Do While .readyState <> 4: DoEvents: Loop
End With
ie.document.parentWindow.execScript "javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(""dgITMatrix:0:lnkBtnDownload"", """", true, """", """", false, true))"
Dim o As IUIAutomation
Dim e As IUIAutomationElement
Dim iCnd As IUIAutomationCondition
Set o = New CUIAutomation
h = ie.Hwnd
h = FindWindowEx(h, 0, "Frame Notification Bar", vbNullString)
If h = 0 Then Exit Sub
Set e = o.ElementFromHandle(ByVal h)
Set iCnd = o.CreatePropertyCondition(UIA_NamePropertyId, "Open")
Dim Button As IUIAutomationElement
Set Button = e.FindFirst(TreeScope_Subtree, iCnd)
Dim InvokePattern As IUIAutomationInvokePattern
Set InvokePattern = Button.GetCurrentPattern(UIA_InvokePatternId)
InvokePattern.Invoke
ActiveWorkbook.SaveAs "I:\Cap_Rel\raw_scrapes\Texas_Gas_Transmission\parsed\Texas_Gas_Transmission_CapRel" & Format(Date - 1, "yyyymmdd") & "MACRO", FileFormat:=xlCSV
End Sub

Verify private key in signed XML with public key

I use javascript to open CAPICOM store to choose certificate.
After that I export selected certificate, public key and private key of that certificate and put them in three hidden fields.
var privateKey = certificates.Item(1).PrivateKey;
var cert = certificates.Item(1);
var publicKey = cert.PublicKey().EncodedKey.Value
When signing xml I used:
To take certificate
Dim hideCertCapicom As String = Replace(HiddenCert.Value, " ", "+")
Dim certificate As New X509Certificate2(Convert.FromBase64String(hideCertCapicom))
For defining private key I used
Dim keyC As String = hideKey
Dim cspp As New CspParameters()
cspp.KeyContainerName = keyC
Dim tmpRsa As New RSACryptoServiceProvider(cspp)
tmpRsa.PersistKeyInCsp = True
This will successfully signed my xml.
For verifying xml I used:
Dim hidePublicKey As String = HiddenPublicKey.Value
Dim keyC As String = hidePublicKey
Dim cspp As New CspParameters()
cspp.KeyContainerName = keyC
Dim tmpRsa As New RSACryptoServiceProvider(cspp)
tmpRsa.PersistKeyInCsp = True
But this doesn't work. It works only if I use the private key again.
Is it good practice to sign and verify with the same private key or to do both with public key?
I was able to sign with private key and verify the signature with public key, and I want to share with you.
In SignXml() function I exported public key from private key:
Dim publicKey as String = tmpRsa.ToXmlString(False)
Then in the same function I call verifyXml() function:
Dim verifySign As Boolean
verifySign = VerifyXml(doc, publicKey)
In verifyXml() function I took public key on this way:
Public Function VerifyXml(Doc As XmlDocument, Key As String) As Boolean
Dim tmpRsa As New RSACryptoServiceProvider()
tmpRsa.FromXmlString(Key)
Dim signedXml As New SignedXml(Doc)
Dim nodeList As XmlNodeList = Doc.GetElementsByTagName("Signature")
If nodeList.Count <= 0 Then
Throw New CryptographicException("Verification failed: No Signature was found in the document.")
End If
If nodeList.Count >= 2 Then
Throw New CryptographicException("Verification failed: More that one signature was found for the document.")
End If
signedXml.LoadXml(DirectCast(nodeList(0), XmlElement))
Return signedXml.CheckSignature(tmpRsa)
End Function

Xml.XmlDataDocument() obsolete message

I am running a simple program in which you enter a user number into a text box, click the submit button, and then the program is supposed to go to a database look up the number you entered and display that rows information. Simple enough.
The problem is I keep getting the error that Xml.XmlDataDocument() is obsolete. I've googled this issue, which led me to here, but the replacements suggested do not work within my program.
Also, I have not studied VB and this is for an XML class.
I've double checked my code for any errors and do not see anything. But, I could be missing the forest for the trees. Would like to have another set of eyes take a look at my code to see if I've missed something, or to offer up a replacement for the Xml.XmlDataDocument() line.
Thank you in advance for any help you can offer.
Here is the code I am using:
Javascript for the onClick event
<script language="javascript" type="text/javascript">
function btnSearch_onclick() {
var docSubmit = new ActiveXObject("MSXML2.DOMDocument");
docSubmit.loadXML("<?xml version='1.0'?><request><customerID>" + txtCustID.value + "</customerID></request>")
var objSocket = new ActiveXObject("MSXML2.XMLHTTP");
objSocket.open("POST", "Lookup.aspx", false)
objSocket.send(docSubmit)
alert(objSocket.responseXML.xml)
lblFirstName.innerHTML = objSocket.responseXML.selectSingleNode("//FirstName").firstChild.nodeValue
lblLastName.innerHTML = objSocket.responseXML.selectSingleNode("//LastName").firstChild.nodeValue
lblAddress.innerHTML = objSocket.responseXML.selectSingleNode("//Address").firstChild.nodeValue
lblCity.innerHTML = objSocket.responseXML.selectSingleNode("//City").firstChild.nodeValue
lblState.innerHTML = objSocket.responseXML.selectSingleNode("//State").firstChild.nodeValue
lblZip.innerHTML = objSocket.responseXML.selectSingleNode("//Zip").firstChild.nodeValue
}
</script>
And here is the VB code:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim docReceived As New System.Xml.XmlDataDocument()
docReceived.Load(Request.InputStream)
Dim CustomerID = docReceived.SelectSingleNode("//customerID").FirstChild.Value
Dim myConnection As New System.Data.OleDb.OleDbConnection
Dim myConnectionString As String
myConnectionString = "Provider = Microsoft.Jet.OLEDB.4.0;Data Source = " & _
Server.MapPath("customer.mbd")
myConnection.ConnectionString = myConnectionString
Dim strSQL As String
strSQL = "Select * From CustomerInfo where CustomerID = " & CustomerID
Dim myAdapter As New System.Data.OleDb.OleDbDataAdapter(strSQL, myConnection)
Dim myDataSet As New System.Data.DataSet("CustomerInfo")
Dim intRecords As Integer
intRecords = myAdapter.Fill(myDataSet, "Customer")
Response.ContentType = "text/xml"
If intRecords > 0 Then
myDataSet.WriteXml(Response.OutputStream)
Else
Response.Write("<?xml version='1.0'?><customer><FirstName>Not Found</FirstName><LastName>***</LastName><Address>***</Address><City>***</City><State>***</State><Zip>***</Zip><Phone>***</Phone><Email>***</Email></customer>")
End If
myDataSet.WriteXml(Response.OutputStream)
myConnection.Close()
myAdapter.Dispose()
myConnection.Dispose()
End Sub
XmlDataSet is obsolete. As you can see on the msdn it may even be removed in the next version of the .NET Framework ([ObsoleteAttribute("XmlDataDocument class will be removed in a future release.")]
). In your case I don't think you need it at all. The easies fix seems to be to use just XmlDocument. I believe you won't have to change anything else in your code but this line
Dim docReceived As New System.Xml.XmlDataDocument()
to:
Dim docReceived As New System.Xml.XmlDocument()

Categories

Resources