473,769 Members | 2,372 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

XML File Question?

Can XML files be easily encrypted?

Nov 21 '05 #1
3 1588
I hope this will help
1 interface, 3 classes and 1 form

1.Interface ISXMLCipherKey. vb (create as class)
----------------------------------------------------------------
Imports System

Public Interface ISXMLCipherKey

ReadOnly Property CipherKey() As Byte()
Sub CipherKeyFinali ze()

End Interface

=============== =============== =============== ==========
2.Class SecureXML.vb
----------------------------------------------------------------
Imports System
Imports System.Xml
Imports System.IO
Imports System.Security .Cryptography

Public Structure SXMLDataHeader
Public token As Int32
Public Length As Int32
End Structure

Public Class SecureXML
Implements IDisposable

Public Const SXML_DATAHEADER _TOKEN As Int32 = &H190298

Private _ciphertext As MemoryStream
Private _cipherkey As ISXMLCipherKey
Private _cipherIV As Byte() = {&HA1, &HFF, &H1F, &H22, &HF0, &HBB,
&HBF, &HFB, &HCB, &H9A, &H2C, &H87, &H0, &HF, &H7D, &HDC}

Public Sub New(ByVal cipherkey As ISXMLCipherKey)
_ciphertext = New MemoryStream
_cipherkey = cipherkey
End Sub

Public Sub Dispose() Implements IDisposable.Dis pose
_ciphertext.Set Length(0)
_ciphertext = Nothing
_cipherkey = Nothing
End Sub

Public Sub Save(ByVal xmldoc As System.Xml.XmlD ocument, ByVal output
As Stream)
Dim alg As New RijndaelManaged
Dim encryptor As ICryptoTransfor m
Dim streamwriter As New BinaryWriter(ou tput)
Dim headerinfo As New SXMLDataHeader
Dim cipherStream As CryptoStream

_cipherkey.Ciph erKeyFinalize()
alg.Key = _cipherkey.Ciph erKey
alg.IV = _cipherIV
encryptor = alg.CreateEncry ptor()

cipherStream = New CryptoStream(_c iphertext, encryptor,
CryptoStreamMod e.Write)
'Save XML Encrypted
xmldoc.Save(cip herStream)

'Flush Our CipherStream Data to our CipherText Stream
cipherStream.Fl ushFinalBlock()

headerinfo.toke n = SXML_DATAHEADER _TOKEN
headerinfo.Leng th = _ciphertext.Len gth

'Output our header info to the output stream
WriteHeader(hea derinfo, streamwriter)
'Write Our CipherText to the end of the output stream
_ciphertext.Wri teTo(output)

'Reset for next use
Reset()
End Sub

Public Function Load(ByVal input As Stream) As
System.Xml.XmlD ocument
Dim streamreader As New BinaryReader(in put)
Dim headerinfo As SXMLDataHeader
Dim alg As New RijndaelManaged
Dim encryptor As ICryptoTransfor m
Dim cipherStream As CryptoStream

Dim xmldoc As New System.Xml.XmlD ocument

If Not ReadHeader(head erinfo, streamreader) Then
Return Nothing
End If

'Buffer the data from the input stream into our ciphertext
stream
_ciphertext.Wri te(streamreader .ReadBytes(head erinfo.Length), 0,
headerinfo.Leng th)

'Seek to the beginning of the ciphertext stream
_ciphertext.See k(0, SeekOrigin.Begi n)

'Init Decryption Alg
_cipherkey.Ciph erKeyFinalize()
alg.Key = _cipherkey.Ciph erKey
alg.IV = _cipherIV
encryptor = alg.CreateDecry ptor()

cipherStream = New CryptoStream(_c iphertext, encryptor,
CryptoStreamMod e.Read)

'Load our unencrypted XML Data
xmldoc.Load(cip herStream)

'Reset for next use
Reset()

'Return the new XML Doc to the user
Return xmldoc
End Function

Private Sub WriteHeader(ByV al header As SXMLDataHeader, ByVal output
As BinaryWriter)
output.Write(he ader.token)
output.Write(he ader.Length)
End Sub

Private Function ReadHeader(ByRe f header As SXMLDataHeader, ByVal
input As BinaryReader) As Boolean
Dim hdr As New SXMLDataHeader

hdr.token = input.ReadInt32 ()

If hdr.token <> SXML_DATAHEADER _TOKEN Then
Return False
End If

hdr.Length = input.ReadInt32 ()

If hdr.Length <= 0 Or hdr.Length > (input.BaseStre am.Length)
Then
Return False
End If

header = hdr
Return True
End Function

Public Sub Reset()
_ciphertext = Nothing
_ciphertext = New MemoryStream
End Sub
End Class
=============== =============== =============== ==========
3.Class SXMLComputerCip herKey.vb
----------------------------------------------------------------
Imports System
Imports System.Security .Cryptography
Imports System.IO

Public Class SXMLComputerCip herKey
Implements ISXMLCipherKey

Private _ComputerDrive As String
Private _cipherKey As Byte()

Public Sub New(ByVal harddriveletter As String)
_ComputerDrive = harddriveletter
End Sub

Public Sub CipherKeyFinali ze() Implements
ISXMLCipherKey. CipherKeyFinali ze
Dim _md5 As New MD5CryptoServic eProvider
Dim encoder As New Text.ASCIIEncod ing
Dim _tmpStr As String

Throw New
NotSupportedExc eption("SXMLCom puterCipherKey: :CipherKeyFinal ize() has
not yet been implmented and/or completed!")
End Sub

Public ReadOnly Property CipherKey() As Byte() Implements
ISXMLCipherKey. CipherKey
Get
Return _cipherKey
End Get
End Property
End Class

=============== =============== =============== ==========
4.Class SXMLCipherKey.v b
----------------------------------------------------------------
Imports System
Imports System.IO
Imports System.Security .Cryptography

Public Class SXMLCipherKey
Implements ISXMLCipherKey

Private _keydata As String
Private _cipherkey As Byte()

Public Sub New(ByVal pass As String)
_keydata = pass
End Sub

Public Sub CipherKeyFinali ze() Implements
ISXMLCipherKey. CipherKeyFinali ze
Dim encoder As New Text.ASCIIEncod ing
Dim _tmpbytes As Byte()
Dim _md5 As New MD5CryptoServic eProvider

_tmpbytes = encoder.GetByte s(_keydata)
_cipherkey = _md5.ComputeHas h(_tmpbytes)
End Sub

Public ReadOnly Property CipherKey() As Byte() Implements
ISXMLCipherKey. CipherKey
Get
Return _cipherkey
End Get
End Property
End Class

=============== =============== =============== ==========
Form1
Imports System.IO.Path

Public Class Form1
Inherits System.Windows. Forms.Form

#Region " Windows Form Designer generated code "

Public Sub New()
MyBase.New()

'This call is required by the Windows Form Designer.
InitializeCompo nent()

'Add any initialization after the InitializeCompo nent() call

End Sub

'Form overrides dispose to clean up the component list.
Protected Overloads Overrides Sub Dispose(ByVal disposing As
Boolean)
If disposing Then
If Not (components Is Nothing) Then
components.Disp ose()
End If
End If
MyBase.Dispose( disposing)
End Sub

'Required by the Windows Form Designer
Private components As System.Componen tModel.IContain er

'NOTE: The following procedure is required by the Windows Form
Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
Friend WithEvents TextBox1 As System.Windows. Forms.TextBox
Friend WithEvents Button1 As System.Windows. Forms.Button
Friend WithEvents Button2 As System.Windows. Forms.Button
Friend WithEvents Label1 As System.Windows. Forms.Label
Friend WithEvents Button3 As System.Windows. Forms.Button
Friend WithEvents btnExit As System.Windows. Forms.Button
<System.Diagnos tics.DebuggerSt epThrough()> Private Sub
InitializeCompo nent()
Me.TextBox1 = New System.Windows. Forms.TextBox
Me.Button1 = New System.Windows. Forms.Button
Me.Button2 = New System.Windows. Forms.Button
Me.Label1 = New System.Windows. Forms.Label
Me.Button3 = New System.Windows. Forms.Button
Me.btnExit = New System.Windows. Forms.Button
Me.SuspendLayou t()
'
'TextBox1
'
Me.TextBox1.Loc ation = New System.Drawing. Point(4, 23)
Me.TextBox1.Nam e = "TextBox1"
Me.TextBox1.Siz e = New System.Drawing. Size(264, 20)
Me.TextBox1.Tab Index = 0
Me.TextBox1.Tex t = ""
'
'Button1
'
Me.Button1.Loca tion = New System.Drawing. Point(8, 56)
Me.Button1.Name = "Button1"
Me.Button1.TabI ndex = 1
Me.Button1.Text = "Encrypt"
'
'Button2
'
Me.Button2.Loca tion = New System.Drawing. Point(100, 56)
Me.Button2.Name = "Button2"
Me.Button2.TabI ndex = 2
Me.Button2.Text = "Decrypt"
'
'Label1
'
Me.Label1.Locat ion = New System.Drawing. Point(20, -1)
Me.Label1.Name = "Label1"
Me.Label1.Size = New System.Drawing. Size(248, 23)
Me.Label1.TabIn dex = 3
Me.Label1.Text = "Enter XML file to encrypt"
Me.Label1.TextA lign =
System.Drawing. ContentAlignmen t.MiddleCenter
'
'Button3
'
Me.Button3.Loca tion = New System.Drawing. Point(270, 24)
Me.Button3.Name = "Button3"
Me.Button3.Size = New System.Drawing. Size(28, 23)
Me.Button3.TabI ndex = 4
Me.Button3.Text = "..."
'
'btnExit
'
Me.btnExit.Loca tion = New System.Drawing. Point(196, 56)
Me.btnExit.Name = "btnExit"
Me.btnExit.TabI ndex = 8
Me.btnExit.Text = "Exit"
'
'Form1
'
Me.AutoScaleBas eSize = New System.Drawing. Size(5, 13)
Me.ClientSize = New System.Drawing. Size(308, 86)
Me.Controls.Add (Me.btnExit)
Me.Controls.Add (Me.Button3)
Me.Controls.Add (Me.Label1)
Me.Controls.Add (Me.Button2)
Me.Controls.Add (Me.Button1)
Me.Controls.Add (Me.TextBox1)
Me.Name = "Form1"
Me.Text = "Form1"
Me.ResumeLayout (False)

End Sub

#End Region

Dim files(2) As String
Dim mykey As New SXMLCipherKey(" Iouri")
Dim encstrm As IO.FileStream
Dim sxml As New SecureXML(mykey )

Dim sFile As String

'encrypt
Private Sub Button1_Click(B yVal sender As System.Object, ByVal e As
System.EventArg s) Handles Button1.Click
files(0) = TextBox1.Text
files(1) = TextBox1.Text.S ubstring(0, TextBox1.Text.L ength -
sFile.Length) & "Encrypted. xml"
Me.EncryptXML()
MessageBox.Show ("XML file is encrypted")
End Sub

'decrypt
Private Sub Button2_Click(B yVal sender As System.Object, ByVal e As
System.EventArg s) Handles Button2.Click
files(1) = TextBox1.Text.S ubstring(0, TextBox1.Text.L ength -
sFile.Length) & "Encrypted. xml"
files(2) = TextBox1.Text.S ubstring(0, TextBox1.Text.L ength -
sFile.Length) & "Decrypted. xml"
Me.DecryptXML()
MessageBox.Show ("XML file is decrypted")
End Sub
Private Sub EncryptXML()
Dim xmldoc As New Xml.XmlDocument

'crate Encrypted xml
encstrm = New IO.FileStream(f iles(1), IO.FileMode.Ope nOrCreate)

xmldoc.Load(fil es(0))

sxml.Save(xmldo c, encstrm)
encstrm.Flush()
encstrm.Close()

End Sub
Private Sub DecryptXML()
'create decrypted xml
encstrm = New IO.FileStream(f iles(1), IO.FileMode.Ope nOrCreate)
encstrm.Seek(0, IO.SeekOrigin.B egin)

sxml.Reset()
Dim newxml As Xml.XmlDocument
newxml = sxml.Load(encst rm)

newxml.Save(fil es(2))
End Sub

Private Sub Button3_Click(B yVal sender As System.Object, ByVal e As
System.EventArg s) Handles Button3.Click
Dim od As New OpenFileDialog
With od
.InitialDirecto ry = "..\XMLFile s\"
.Filter = "XML Files (*)|;*.xml"
If .ShowDialog() = DialogResult.OK Then
TextBox1.Text = GetFullPath(.Fi leName) 'see import on
the top
sFile = GetFileName(.Fi leName)
End If
End With

If TextBox1.Text.L ength = 0 Then
MessageBox.Show ("Enter XML file")
Exit Sub
End If

End Sub

Private Sub btnExit_Click(B yVal sender As System.Object, ByVal e As
System.EventArg s) Handles btnExit.Click
Me.Close()
End Sub

End Class


"Debbie Carter" <dc*********@sb cglobal.net> wrote in message
news:M4******** **********@news svr31.news.prod igy.com:
Can XML files be easily encrypted?


Nov 21 '05 #2
Scorpion...than k you VERY much!

Debbie

Nov 21 '05 #3
Anytime....
"Debbie Carter" <dc*********@sb cglobal.net> wrote in message
news:oV******** **********@news svr33.news.prod igy.com:
Scorpion...than k you VERY much!

Debbie


Nov 21 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
3647
by: BoonHead, The Lost Philosopher | last post by:
I think the .NET framework is great! It's nice, clean and logical; in contradiction to the old Microsoft. It only saddens me that the new Microsoft still doesn't under stand there own rules when it comes to file paths. A lot of Microsoft installers for example, and also installers of other companies, do not work because they handle paths in the following manner:
1
3419
by: Marc Cromme | last post by:
I would like to ask a question about (good ?) style and possibilities in mixing C FILE* and C++ file streams. The background is that I want to use the C libpng library from within C++, but I would like to open C++ file streams due to easier exception handeling and safe closure of file ressources. Question 1: I open a standard file stream and want to transfer some binary read bits
21
4698
by: siroregano | last post by:
Hi Everyone- I'm new to this group, and almost-as-new to asking programming questions publicly, so please forgive me if I miss a convention or two! I have a text file, around 40,000 lines long, where each line is a string of 4 ASCII characters corresponding to a 12-bit hexadecimal audio sample. The file reads something like this... 081F
9
2415
by: CGW | last post by:
I asked the question yesterday, but know better how to ask it, today: I'm trying to use the File.Copy method to copy a file from a client to server (.Net web app under IIS ). It looks to me that when I give a path like @"C:\holdfiles\myfile.txt" it looks on the server C drive. How do I pull from the client? Do I need a different class and/or method? Filestream? -- Thanks,
22
4007
by: petermichaux | last post by:
Hi, I'm curious about server load and download time if I use one big javascript file or break it into several smaller ones. Which is better? (Please think of this as the first time the scripts are downloaded so that browser caching is out of the equation.) Thanks, Peter
2
2128
by: sani8888 | last post by:
Hi everybody I am a beginner with C++ programming. And I need some help. How can I start with this program *********** The program is using a text file of information as the source of the questions. The program starts by outputting a simple text information screen: Question Master
12
13438
by: dbuchanan | last post by:
Hello, (Is this the proper newsgroup?) === Background === I am building a solution with two projects. One project is my data access layer which contains my DataSet as an xsd file. The XSD file was built by draging tables from the Data Sources pane. Auto-generated code created the files associated wtih the XSD file (xss,
6
2488
by: portCo | last post by:
Hello there, I am creating a vb application which is some like like a questionare. Application read a text file which contains many questions and display one question and the input is needed from user to calculate the score. Here is a problem. I can read a text file. However, it's read whole file at a time. So,
4
9073
by: saytri | last post by:
Hi guys! I am making a quiz. The questions are stored in a binary file. I made an option in the quiz where a user can add a question to the binary file. Altough this works, the problem is that whenever a user enters a new question is just overwrites the whole file, instead of adding it to the rest of the questions in the binary file. Do i have something wrong? Thanks a lot. :-) This is the piece of code that adds a question to binary file:...
14
12828
by: =?Utf-8?B?R2lkaQ==?= | last post by:
Hi, In my windows applicationm, i need to excute a batch file. this batch file throws some text and questions to the screen, i need to catch the standard Output, check if it's a question, in case it's a question, i want to popup a messageBox or something, and bring back to the batch file the result (Yes\No question). I know how to excute the batch file and get all the Standard output at the end, but i don't know who can i read it line by...
0
9579
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10199
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10035
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9981
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9850
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8862
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7396
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5436
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2810
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.