Encryption and Decryption of string with out using Base64String [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
How to encrypt Decrypt text without using Base64String?
I don't want to use Base64String because encrypted text should not contains any special character like #, $, #, /, \, |,=,% ,^

Well the obvious approach if you don't want to use base64 is to use base16 - i.e. hex.
There are plenty of examples of converting between a byte array and a hex string representation on Stack Overflow. (BitConverter.ToString(data).Replace("-", "") is an inefficient way of performing the conversion to a string; there's nothing quite as simple for the reverse, but it's not much code.)
EDIT: As noted in comments, SoapHexBinary has a simple way of doing this. You may wish to wrap the use of that class in a less SOAP-specific type, of course :)
Of course that will use rather more space than base64. One alternative is to use base64, but using a different set of characters: find 65 characters you can use (the 65th is for padding) and encode it that way. (You may find there's a base64 library available which allows you to specify the characters to use, but if not it's pretty easy to write.)
Do not try to just use a normal Encoding - it's not appropriate for data which isn't fundamentally text.
EDIT: As noted in comments, you can use base32 as well. That can be case-insensitive (potentially handy) and you can avoid I/1 and O/0 for added clarity. It's harder to code and debug though.

There's a great example in the MySQL Connector source code for the ASP.NET membership provider implementation. It may be a little hassle to download and research, but it has a well-established encryption and decryption module in there.
http://dev.mysql.com/downloads/connector/net/#downloads
Choose the 'source code' option before downloading.
If you want encoding/decoding for data transmission or condensed character storage, you should edit your question. Answers given to an encoding question will be much different than answers given to an encryption/decryption question.

Related

Class encryption in c sharp [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I need to create an encryption class that does not accept special characters,that uses letters and numbers only.
Does anyone have one or can you help me develop it?
You don't need to create a separate encryption algorithm to do this. Just use the following regex to validate your input:
[A-Za-z0-9]+
This will validate that the input only contains alphanumeric charactrs. After that, you can perform whatever encryption you want.
So, basically, you could have a class like the following (and I'm mixing C# and pseudocode here):
public class Encryption {
private readonly Regex regex = new Regex("[A-Za-z0-9]+");
public string Encrypt(string toEncrypt) {
if (toEncrypt == null)
throw new ArgumentNullException("toEncrypt");
// This check is very important
// If toEncrypt contains non-alphanumeric characters, is an empty string, or consists only of whitespace don't accept it
if (!regex.IsMatch(toEncrypt))
throw new ArgumentException("String is not alphanumeric");
// Obviously pseudocode
// Replace this line with a call to AES, 3DES, Twofish, Caesar Cipher, or whatever encryption algorithm you want
return EncryptionAlgorithm.Encrypt(toEncrypt, whateverKey);
}
}
The term "encryption" is actually pretty vague in this case. If you're looking for "serious" encryption, you probably want to use either Twofish or the Advanced Encryption Standard (AES); both are highly secure at this point and have good library support, but AES is somewhat better studied. The other AES contest finalists (such as Serpent) are also highly secure, but they tend not to be studied as thoroughly or have as good of library support as Twofish and AES. Unless you have a good reason to use Twofish or one of the other AES contest finalists instead of AES, it's probably better to just use AES.
I say "highly secure at this point" because security's intrinsically relative to current technology; for example, public-key cryptography would be broken by quantum computers. DES was considered secure until hardware became fast enough to brute-force it. (In fact, it's still considered relatively secure against other kinds of attacks, such as differential crypanalysis).
Note that if you're serious about security it's rarely a good idea to try to design your own algorithm.
There are also classical ciphers like the Caesar Cipher available. You should only use these if you don't care about security at all as they're all badly broken at this point. They aren't built into the .NET framework but most of them are pretty easy to implement yourself.
Encryption produces binary output, not characters, if you need a character representation use Base64 or hexadecimal encoding.

I need an algorithm to create vouchers based on date and amount of time [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I need an algorithm that creates vouchers that is based on an internet kiosk timer. Basically, voucher should have the amount of time allowed encrypted into it. I was thinking of having the amount of time in hex at the start with a few random chars after it then a checksum at the end. However any other ideas are welcome
Use c# builtin libraries for encryption. Since you are the only entity that needs to encrypt/decrypt you can use either a asymetric key(public/private) schema, where you keep both keys private or a symmetric key solution.
Make sure the keys are sufficiently large so that they are not easy to break (at least 256 bits, preferably more).
You don't need to add random chars at the start. You don't need to add checksum at the end. The encryption library should fail to decrypt if the content has been tampered with (accidental character change, but will not stop a very determined attacker). If you want to be extra sure there's been no tampering generate an additional public/private keys and use them to sign the encrypted string.
If you don't care that users can see your voucher string, you can just put it in plain text and just use the libraries to sign it.
So all you need is to have a class that is serializable and contains all the fields of your voucher. Get the serialized string and pass it through the encryption/signing routines. When you get it backs use the same routines to make sure the string is authentic then deserialize it and you have your data.
The most important thing is to use the libraries correctly (follow the tutorials, instructions) and you keep your keys safe.

.NET How to get an int comming throught a socket C-Sharp [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Here is my problem :
I'm used to receive data like int, char* & cie... throught a TCP socket in c/c++, but how to manage that in c#? I will communicate with a c++ server, sending me int, bools and char*. I think my bigger problem come from the fact than a char in c# = 2bytes ...
Thanks a lot, and sorry for my poor english :/
Firstly, I really hope you aren't actually sending a char*, as that makes zero sense outside of a given process, and isn't even a well-defined length.
Basically, you need to sit down and write down the encoding rules for all the things you are sending. For example, you might say:
int is 4 bytes little-endian
text is utf-8 encoded with a length-prefix (bytes, not characters) as an int
a bool is a single byte (to avoid boundary issues)
etc for every data type you need
Then figure out how you are going to partition multiple fields of a single message, and how you are going to frame multiple messages in the same socket.
Or perhaps a better option is to choose one of the many pre-existing serialization formats and offload the thinking to that. If you are after efficiency, then "protocol buffers" would be an excellent choice. If you want simplicity maybe JSON.
If you still want to hand-code it, then : start by writing down what exactly it is going to look like on the wire, then implement that.

RSACryptoServiceProvider helper [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I was looking for RSACryptoServiceProvider helper and found two different implementations
1) http://www.cnblogs.com/WYB/archive/2008/06/19/1225704.html
2) https://github.com/robvolk/Helpers.Net/blob/master/Src/Helpers.Net/EncryptionExtensions.cs
both of them working
var encryptedBytes = myBytes.RSAEncrypt(publicKey);
System.Text.Encoding.Unicode.GetString(encryptedBytes);
returns strings like "蹩巷Ӂය馧㾵봽놶徤蕺蓷課Ϝ堲泍썳⁙䃑ക늏...."
myString.EncryptStringUsingXMLFile(publicKey)
returns strings like "AnvFFT6YpoiAyIFwl+tueZq56Zcb0B7WhBEvz5uWl...."
May be some one can explain why first one producing Chinese strings and how to change that?
What approach is better?
To answer your first question. While it may look like it is producing Chinese characters what is actually happening is it is turning a byte array into unicode. In c# typically when you want to store a byte array you convert it to base64 which is what your second example appears to return.
Your first example would become this:
var encryptedBytes = myBytes.RSAEncrypt(publicKey);
Convert.ToBase64String(encryptedBytes) // this line changed
returns strings like "AnvFFT6YKpoiAy...."
As for what is recommended, the most common is to use base64. The reasons people use base64 over unicode or UTF-8 for binary data can be found in these answers:
https://stackoverflow.com/a/201491/701062
MSDN - Convert.ToBase64String(byte[])
http://msdn.microsoft.com/en-us/library/dhx0d524(v=vs.100).aspx
MSDN - Convert.FromBase64String(string) - Useful if you need to convert back into a byte array
http://msdn.microsoft.com/en-us/library/system.convert.frombase64string(v=vs.100).aspx

What are the best practices for handling Unicode strings in C#? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Can somebody please provide me some important aspects I should be aware of while handling Unicode strings in C#?
Keep in mind that C# strings are sequnces of Char, UTF-16 code units. They are not Unicode code-points. Some unicode code points require two Char's, and you should not split strings between these Chars.
In addition, unicode code points may combine to form a single language 'character' -- for instance, a 'u' Char followed by umlat Char. So you can't split strings between arbitrary code points either.
Basically, it's mess of issues, where any given issue may only in practice affect languages you don't know.
C# (and .Net in general) handle unicode strings transparently, and you won't have to do anything special unless your application needs to read/write files with specific encodings. In those cases, you can convert managed strings to byte arrays of the encoding of your choice by using the classes in the System.Text.Encodings namespace.
System.String already handled unicode internally so you are covered there. Best practice would be to use System.Text.Encoding.UTF8Encoding when reading and writing files. It's more than just reading/writing files however, anything that streams data out including network connections is going to depend upon the encoding. If you're using WCF, it's going to default to UTF8 for most of the bindings (in fact most don't allow ASCII at all).
UTF8 is a good choice because while it still supports the entire Unicode character set, for the majority of the ASCII character set it has a byte similarity. Thus naive applications that don't support Unicode have some chance of reading/writing your applications data. Those applications will only begin to fail when you start using extended characters.
System.Text.Encoding.Unicode will write UTF-16 which is a minimum of two bytes per character, making it both larger and fully incompatible with ASCII. And System.Text.Encoding.UTF32 as you can guess is larger still. I'm not sure of the real-world use case of UTF-16 and 32, but perhaps they perform better when you have large numbers of extended characters. That's just a theory, but if it is true, then Japanese/Chinese developers making a product that will be used primarily in those languages might find UTF-16/32 a better choice.
Only think about encoding when reading and writing streams. Use TextReader and TextWriters to read and write text in different encodings. Always use utf-8 if you have a choice.
Don't get confused by languages and cultures - that's a completely separate issue from unicode.
.Net has relatively good i18n support. You don't really need to think about unicode that much as all .Net strings and built-in string functions do the right thing with unicode. The only thing to bear in mind is that most of the string functions, for example DateTime.ToString(), use by default the thread's culture which by default is the Windows culture. You can specify a different culture for formatting either on the current thread or on each method call.
The only time unicode is an issue is when encoding/decoding strings to and from bytes.
As mentioned, .NET strings handle Unicode transparently. Besides file I/O, the other consideration would be at the database layer. SQL Server for instance distinguishes between VARCHAR (non-unicode) and NVARCHAR (which handles unicode). Also need to pay attention to stored procedure parameters.
More details can be found on this thread:
http://discuss.joelonsoftware.com/default.asp?dotnet.12.189999.12

Categories