encrypt RSA by long text parts - rsa

Good afternoon,
Does anyone have any solution to encrypt large text in blocks using RSA algorithm
In the example below it works for small texts, the more I try the more large texts generates an error.
Dim RSA = New RSACryptoServiceProvider(1024)
Dim dataToEncrypt() As Byte = Encoding.UTF8.GetBytes("2010-05-18;2010-05-18T15:25;FAC 001/19;75.00;")
Dim privKey = RSA.ExportParameters(True)
Dim pubKey = RSA.ExportParameters(False)
RSA.ImportParameters(pubKey)
Dim encryptedData As Byte() = RSA.Encrypt(dataToEncrypt, False)
RSA.ImportParameters(privKey)
Dim EncryptedResult As String = System.Convert.ToBase64String(encryptedData)
Dim EncrypetdResult As String = System.Text.Encoding.[Default].GetString(encryptedData)
Dim decryptedData As Byte() = RSA.Decrypt(encryptedData, False)
Dim texto = Encoding.UTF8.GetString(decryptedData)
best regards
omateus

Related

How to use CATIA CatScript macro to capture a specific view of a part?

I am tasked to find a way to help our design team to screen capture a specific position of a part. However, I don't know how to customize my own position.
I tried looking at some codes on the internet and I found this:
Sub CATMain()
Dim productDocument1 As Document
Set productDocument1 = CATIA.ActiveDocument
Dim cameras1 As Cameras
Set cameras1 = productDocument1.Cameras
Dim camera3D1 As Camera
Set camera3D1 = cameras1.Item(1)
Dim viewpoint3D1 As Viewpoint3D
Set viewpoint3D1 = camera3D1.Viewpoint3D
Dim specsAndGeomWindow1 As Window
Set specsAndGeomWindow1 = CATIA.ActiveWindow
Dim viewer3D1 As Viewer
Set viewer3D1 = specsAndGeomWindow1.ActiveViewer
viewer3D1.Viewpoint3D = viewpoint3D1
Set viewpoint3D1 = camera3D1.Viewpoint3D
viewer3D1.Viewpoint3D = viewpoint3D1
Dim filelocation As String
filelocation = "c:\Temporary\"
Dim extension As String
extension = ".jpg"
Dim Name as string
Name= filelocation & "right" & extension
viewer3D1.Viewpoint3D =camera3D1.Viewpoint3D
CATIA.ActiveDocument.Selection.Clear()
viewer3D1.Capturetofile 5,Name
Dim camera3D2 As Camera
Set camera3D2 = cameras1.Item(2)
Dim viewpoint3D2 As Viewpoint3D
Set viewpoint3D2 = camera3D2.Viewpoint3D
viewer3D1.Viewpoint3D = viewpoint3D2
Set viewpoint3D2 = camera3D2.Viewpoint3D
viewer3D1.Viewpoint3D = viewpoint3D2
Name = filelocation & "left" & extension
viewer3D1.Viewpoint3D =camera3D2.Viewpoint3D
CATIA.ActiveDocument.Selection.Clear()
viewer3D1.Capturetofile 5,Name
End Sub
Is there a way to tweak this code in terms of my own position that I want?
Thank you!

Updated Yahoo Weather API - .NET

I'm trying to implement the newest yahoo weather API in a .NET application (the one we were using was discontinued in favor of this new one): https://developer.yahoo.com/weather/documentation.html#commercial
Their only examples are in PHP and Java. I've done my best to convert the Java example to .NET but I still am getting a "401 - Unauthorized" response. I've gone over my code several times and cannot find any problems so I'm hoping someone else will be able to see where I went wrong. Code is below.
Private Sub _WeatherLoader_DoWork(sender As Object, e As DoWorkEventArgs)
Try
Dim oauth As New OAuth.OAuthBase
Dim forecastRssResponse As query
Dim appId As String = My.Settings.YahooAppID
Dim consumerKey As String = My.Settings.YahooAPIConsumerKey
Dim yahooUri As String = String.Format("{0}?location=billings,mt&format=xml", YAHOO_WEATHER_API_BASE_ENDPOINT)
Dim oAuthTimestamp As Integer = oauth.GenerateTimeStamp()
Dim oAuthNonce As String = oauth.GenerateNonce()
Dim parameters As New List(Of String)
Try
parameters.Add(String.Format("oauth_consumer_key={0}", consumerKey))
parameters.Add(String.Format("oauth_nonce={0}", oAuthNonce))
parameters.Add("oauth_signature_method=HMAC-SHA1")
parameters.Add(String.Format("oauth_timestamp={0}", oAuthTimestamp.ToString()))
parameters.Add("oauth_version=1.0")
' Encode the location
parameters.Add(String.Format("location={0}", HttpUtility.UrlEncode("billings,mt", Encoding.UTF8)))
parameters.Add("format=xml")
' Sort parameters ascending
parameters = parameters.OrderBy(Function(item) item).ToList()
Dim i As Integer = 0
Dim builder As New StringBuilder()
Do While (i < parameters.Count())
builder.Append(String.Format("{0}{1}", If(i > 0, "&", String.Empty), parameters(i)))
i += 1
Loop
Dim signatureString As String = String.Format("GET&{0}&{1}", HttpUtility.UrlEncode(YAHOO_WEATHER_API_BASE_ENDPOINT, Encoding.UTF8), HttpUtility.UrlEncode(builder.ToString(), Encoding.UTF8))
Dim oAuthSignature As String = _CreateOauthSignature(signatureString)
Dim authorizationLine As String = String.Format("OAuth oauth_consumer_key={0}, oauth_nonce={1}, oauth_timestamp={2}, oauth_signature_method=HMAC-SHA1, oauth_signature={3}, oauth_version=1.0", consumerKey, oAuthNonce, oAuthTimestamp, oAuthSignature)
Dim forecastRequest As WebRequest = WebRequest.Create(yahooUri)
forecastRequest.Headers.Add("Authorization", authorizationLine)
forecastRequest.Headers.Add("Yahoo-App-Id", appId)
' Cast to HttpWebRequest to set ContentType through property
CType(forecastRequest, HttpWebRequest).ContentType = "text/xml"
Dim forecastResponse As WebResponse = forecastRequest.GetResponse()
If forecastResponse IsNot Nothing Then
Using responseStream As Stream = forecastResponse.GetResponseStream()
Dim rssDoc As New XmlDocument()
rssDoc.Load(responseStream)
forecastRssResponse = rssDoc.OuterXml().FromXml(Of query)()
End Using
e.Result = forecastRssResponse
End If
Catch ex As Exception
e.Result = Nothing
LoadingManually = False
End Try
Catch ex As Exception
modMain.SendDevErrorEmail(ex, "_WeatherLoader_DoWork in WeatherWidget", "Catch around dowork code in fired from refresh timer event in wether widget")
e.Result = Nothing
LoadingManually = False
End Try
End Sub
Private Function _CreateOauthSignature(baseInfo As String) As String
Dim secretKey As String = String.Format("{0}&", My.Settings.YahooAPIConsumerSecretKey)
Dim encoding As New System.Text.ASCIIEncoding()
Dim keyBytes As Byte() = encoding.GetBytes(secretKey)
Dim messageBytes As Byte() = encoding.GetBytes(baseInfo)
Dim hashMessage As Byte()
Using hmac As New HMACSHA1(keyBytes)
hashMessage = hmac.ComputeHash(messageBytes)
End Using
Return Convert.ToBase64String(hashMessage)
End Function
After painstakingly creating a Java app, pasting in the Java example and stepping through it I found that the issue is in a poorly implemented URL Decode function on the receiving end.
In the Java app, URL Encode uses upper case characters while in .NET HTTPUtility.URLEncode uses lower case characters. This is enough to throw off your signature and cause a 401 - Unauthorized error.
My solution was to create a string extension method that will URL Encode in upper case:
<Extension>
Public Function UppercaseURLEncode(ByVal sourceString As String) As String
Dim temp As Char() = HttpUtility.UrlEncode(sourceString).ToCharArray()
For i As Integer = 0 To temp.Length - 2
If temp(i).ToString().Equals("%", StringComparison.OrdinalIgnoreCase) Then
temp(i + 1) = Char.ToUpper(temp(i + 1))
temp(i + 2) = Char.ToUpper(temp(i + 2))
End If
Next
Return New String(temp)
End Function
Using this extension method my signature gets created exactly like the one in the Java app and I am able to retrieve the response.
Hope this helps other .net programmers with this issue!

CreateChangesetAsync - How to checkin an existing file without knowing enconding or file type (just file path)

i tried to follow the example on how to create a changeset with multiple files: [See link][1]
Although i am a bit stuck at the TFVCItem and ItemContent stage where i don't know how to extract the content and enconding of my file.
Im trying to write some code in order to checkin a file given to me by a filePath and check it in at a given location.
Would anyone care to help me out on how to do this?
This is what i came up so far:
Public Function CreateChangeset(ByVal projectName As String,
ByVal files As Dictionary(Of String, String),
ByVal comment As String) As TfvcChangesetRef
Dim c = TFSConnection.GetClient(Of TfvcHttpClient)
Dim newChangetset = New TfvcChangeset
Dim changes = New List(Of TfvcChange)
For Each fKP In files
Dim fileSource = fKP.Key
Dim fileTarget = fKP.Value
Dim newChange = New TfvcChange
newChange.ChangeType = VersionControlChangeType.Add
Dim newItem = New TfvcItem
newItem.Path = $"&/{projectName}/{fileTarget}"
newItem.ContentMetadata = New FileContentMetadata
'' TODO: How to extract the correct encoding, and type?...
'newItem.ContentMetadata.Encoding = GetFileEncoding(fileSource)
'newItem.ContentMetadata.ContentType = "text/plain"
'newChange.Item = newItem
'' TODO: How to extract the correct content, and type?...
'Dim newContent = New ItemContent
'newContent.Content = "Blabla"
'newContent.ContentType = ItemContentType.RawText
'newChange.NewContent = newContent
changes.Add(newChange)
Next
newChangetset.Changes = changes
newChangetset.Comment = comment
Dim changesetRef = c.CreateChangesetAsync(newChangetset).Result
Return changesetRef
End Function
UPDATE:
Ok so i managed to make it work but i still am not sure how to properly set the ContentType.
I have the choice between ItemContentType.RawText and ItemContentType.Base64Encoded but i am not sure when to use one or the other.
Here is the new code which seems to work:
Public Function CreateChangeset(ByVal projectName As String,
ByVal files As Dictionary(Of String, String),
ByVal comment As String) As TfvcChangesetRef
Dim c = TFSConnection.GetClient(Of TfvcHttpClient)
Dim newChangetset = New TfvcChangeset
Dim changes = New List(Of TfvcChange)
For Each fKP In files
' Extract and build our target and source paths.
Dim fileSource = fKP.Key
Dim fileTarget = fKP.Value
Dim fileName = IO.Path.GetFileName(fileSource)
Dim newChange = New TfvcChange
' Create the new TFVC item which will be checked-in.
Dim newItem = New TfvcItem
newItem.Path = $"$/{projectName}/{fileTarget}/{fileName}"
newItem.ContentMetadata = New FileContentMetadata
' Try to extract the item from the server.
Dim serverItem = c.GetItemAsync(newItem.Path).Result
If serverItem Is Nothing Then
' If the file is not on the server, then its a new file.
newChange.ChangeType = VersionControlChangeType.Add
Else
' Indicate that we are dealing with a file modification
' and specify which version we are editing.
newChange.ChangeType = VersionControlChangeType.Edit
newItem.ChangesetVersion = serverItem.ChangesetVersion
End If
' Read the file content to a stream.
Using reader = New StreamReader(fileSource,
Text.Encoding.Default,
True) ' This last parameter allows to extract the correct encoding.
Dim fileContent As String = String.Empty
' Read all the file content to a string so that we can store
' it in the itemcontent.
' NOTE: reading it also allows to retrieve the correct file enconding.
If reader.Peek() >= 0 Then
fileContent = reader.ReadToEnd
End If
' Set the file enconding and MIME Type.
newItem.ContentMetadata.Encoding = reader.CurrentEncoding.WindowsCodePage
newItem.ContentMetadata.ContentType = System.Web.MimeMapping.GetMimeMapping(fileSource)
newChange.Item = newItem
' Set the file content.
Dim newContent = New ItemContent
newContent.Content = fileContent
' TODO: What should be the logic to set the Content Type? Not too sure...
' If newItem.ContentMetadata.ContentType.StartsWith("text/") Then
newContent.ContentType = ItemContentType.RawText
' Else
' newContent.ContentType = ItemContentType.Base64Encoded
' End If
' Store the content to the change.
newChange.NewContent = newContent
End Using
changes.Add(newChange)
Next
newChangetset.Changes = changes
newChangetset.Comment = comment
Dim changesetRef = c.CreateChangesetAsync(newChangetset).Result
Return changesetRef
End Function

how can we identify ASCII or Unicode Encoded thru Encrypted String?

we are using ASCIIEncoding for saving data we have the new requirement for support an Unicode value (regional language like (Hindi, Gujarati) so we modify the code as below we have not done a big change just change over ASCIIEncoding to UnicodeEncoding.
the issue is we are not able to decrypt old records using UnicodeEncoding
is there any way to identify the encryption method from an encrypted string which is stored in DB
we are using Below Code
Public Function DESEncrypt(ByVal PlainText As String) As String
Dim KeyBArray As Byte()
Dim IVBArray As Byte()
Dim Encryptor As ICryptoTransform
Dim PlainTextBArray As Byte()
'Dim Ascii As New ASCIIEncoding
Dim Ascii As New UnicodeEncoding
Dim I As Integer
Dim Result As String
PlainTextBArray = Ascii.GetBytes(PlainText)
KeyBArray = Convert.FromBase64String(desKey)
IVBArray = Convert.FromBase64String(desIV)
Dim TDES As New TripleDESCryptoServiceProvider
Encryptor = TDES.CreateEncryptor(KeyBArray, IVBArray)
Dim CypherTextBArray(Encryptor.OutputBlockSize - 1) As Byte
CypherTextBArray = Encryptor.TransformFinalBlock(PlainTextBArray, I, PlainTextBArray.Length)
Dim TempBArray(CypherTextBArray.Length - 1) As Byte
For I = 0 To CypherTextBArray.Length - 1
TempBArray(I) = CypherTextBArray(I)
Next
Result = Convert.ToBase64String(TempBArray)
KeyBArray = Nothing
IVBArray = Nothing
Encryptor = Nothing
PlainTextBArray = Nothing
Ascii = Nothing
Return Result
End Function
Public Function DESDecrypt(ByVal CypherText As String) As String
Dim KeyBArray As Byte()
Dim IVBArray As Byte()
Dim CypherTextBArray As Byte()
Dim Decryptor As ICryptoTransform
Dim PlainText As New StringBuilder("")
Dim I As Integer
Dim Result As String = String.Empty
If CypherText <> "" Then
CypherTextBArray = Convert.FromBase64String(CypherText)
KeyBArray = Convert.FromBase64String(desKey)
IVBArray = Convert.FromBase64String(desIV)
If cryptoPrivider = "TripleDES" Or cryptoPrivider = "CITripleDES" Then
Dim TDES As New TripleDESCryptoServiceProvider
Decryptor = TDES.CreateDecryptor(KeyBArray, IVBArray)
Else
Dim DES As New DESCryptoServiceProvider
Decryptor = DES.CreateDecryptor(KeyBArray, IVBArray)
End If
Dim PlainTextBArray(Decryptor.OutputBlockSize - 1) As Byte
PlainTextBArray = Decryptor.TransformFinalBlock(CypherTextBArray, I, CypherTextBArray.Length)
'Result = System.Text.Encoding.ASCII.GetString(PlainTextBArray)
Result = System.Text.Encoding.Unicode.GetString(PlainTextBArray)
End If
KeyBArray = Nothing
IVBArray = Nothing
CypherTextBArray = Nothing
Decryptor = Nothing
PlainText = Nothing
Return Result
End Function
You should use UTF8Encoding instead of UnicodeEncoding. The latter is encoded with UTF16, so not bytes compatible with ASCII. Instead UTF8 is byte compatible with ASCII. Both support all Unicode codes, so there is no loss of information.
But often one is not so lucky to have a superset encoder. So in general you should keep track of the encoding (e.g. in a new field), or just use one encoding (so you convert all your databases).

VBA: Dictionary - Can only retrieve the last entry

This is probably a newbie mistake where I'm not aware of some setting that I haven't changed. Anyways, I'm trying use Dictionary to store a instances of class I've created.
Class cls_Connote is just a container of details.
Public connoteNumber As String
Public despatchDate As Date
Public carrier As String
Public service As String
Public items As Integer
Public weight As Integer
Public cost As Single
Public surchargeType As String
Here is how I'm storing the details into the class then into the dictionary.
Function getSurcharge_tag(givenTag As String, givenCol As String, ByRef dicStore As Dictionary, ByRef counter As Integer)`
Dim tagLen As Integer
Dim conNum, conTag As String
Dim clsSurchargeDetails As New cls_Connote
Dim despatchDate, carrier As String
Dim items, weight As Integer
Dim cost As Single
Range(givenCol).Select
tagLen = Len(givenTag)
Do While (ActiveCell.Value <> "")
conNum = Mid(ActiveCell.Value, 1, Len(ActiveCell.Value) - 1)
conTag = Mid(ActiveCell.Value, Len(ActiveCell.Value) - tagLen + 1, Len(ActiveCell.Value))
If (conTag = givenTag) Then 'Remove: both the Original and Adjusted connote lines
despatchDate = ActiveCell.Offset(0, -2).Value
items = ActiveCell.Offset(0, 10).Value
weight = ActiveCell.Offset(0, 11).Value
cost = ActiveCell.Offset(0, 12).Value
clsSurchargeDetails.connoteNumber = conNum
clsSurchargeDetails.despatchDate = despatchDate
clsSurchargeDetails.carrier = carrier
clsSurchargeDetails.items = items
clsSurchargeDetails.weight = weight
clsSurchargeDetails.cost = cost
clsSurchargeDetails.surchargeType = givenTag
dicStore.Add conNum, clsSurchargeDetails
givenCtr = givenCtr + 1
ActiveCell.EntireRow.Delete
Else
ActiveCell.Offset(1, 0).Select
End If
Loop
End Function
This is how I'm trying to get the connotes out of the Dictionary.
Function displaySurcharges(wrkShtName As String, ByRef dicList As Dictionary)
'Remove the existing worksheet
Dim wrkSht As Worksheet
On Error Resume Next
Set wrkSht = Sheets(wrkShtName)
On Error GoTo 0
If Not wrkSht Is Nothing Then
Worksheets(wrkShtName).Delete
End If
Worksheets.Add(After:=Worksheets(Worksheets.Count)).Name = wrkShtName
populateColumnHeaders
Range("A2").Select
Dim getCon As cls_Connote
Set getCon = New cls_Connote
Dim vPtr As Variant
Dim ptrDic As Integer
For Each vPtr In dicList.Keys
Set getCon = dicList.Item(vPtr)
ActiveCell.Value = getCon.connoteNumber
ActiveCell.Offset(0, 1).Value = getCon.despatchDate
ActiveCell.Offset(0, 2).Value = getCon.carrier
ActiveCell.Offset(0, 12).Value = getCon.items
ActiveCell.Offset(0, 13).Value = getCon.weight
ActiveCell.Offset(0, 15).Value = getCon.cost
ActiveCell.Offset(0, 16).Value = getCon.surchargeType
Set getCon = Nothing
ActiveCell.Offset(1, 0).Select
Next vPtr
End Function
I can see dicList does contain different details, getCon only gets the last entry in the Dictionary.
Any help would be fantastic !
To avoid reusing and adding the same reference within the loop, when you need a new instance (after If (conTag = givenTag)) just ask for one:
Set clsSurchargeDetails = New cls_Connote