Trying to Encrypt/Decrypt using AES. Progress == null; - c#

Edit.
I guess I had a problem with creating a correct input into the encrypt/decrypt methods: These lines of code do the trick:
string encrypted = en.Encrypt(stringBuilder.ToString(), "username", "password");
string decrypted = en.Decrypt(encrypted, "username", "password");
mainWindow.ChangeTextBox = encrypted + Environment.NewLine + decrypted;
I am just playing around and trying to figure out how encryption/decryption by using AES works. I am referring to this article (pretty much copy and paste :( Trying to learn).
There they give me complete encryption/decryption methods which I have tried to modify. I am trying to pass a list of entries created by ArrayList then binded with string builder. It seems like I am able to encrypt data but decryption causes error:
Length of the data to decrypt is invalid.
at line with code:
ByteCount = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length);
How can I implement this code to be useful with my program and work correctly?
Regards.

I haven't looked through the code in detail, but it seems that the order of the parameters on the calls to Encrypt and Decrypt doesn't match the definition of the methods. In the calls to these methods you appear to have username, password, plain/cyphertext; whereas the methods have the signature plain/cyphertext, password, username.

Am I right it's caused for an empty or null string as plaintext? ;-)
"lol1" can not be decrypted as it's not a valid ciphertext length (padding!) not to say it wouldn't make any sense.

Related

c# how to convert aes iv/key byte array into writeable string

I have a small inhouse app (and any advice on other methods is appreciated as well) where I utilize 2 token strings that I'd like to encrypt with aes. While this is a super small app and I don't think there's a huge risk on my local, I'd still like to encrypt them with something. My thought was that I'd:
have a file on my local with the iv/key string that I could read into my app upon running, it'd decrypt the token which is stored in the db and I could use it, and when I have to overwrite the token value I'd create a new aes/triple dev iv/key pair. the iv/key pair lives in a file (or the config of the app) and then the new encrypted token goes to my db.
The problem I'm having (i'm new to encryption) is that all of the tutorials show something like the following:
Aes aes = Aes.Create();
byte[] iv = aes.IV;
byte[] key = aes.Key;
However I'm looking to store the string value, and then when the app runs next and I pull the iv/key pair in I convert it back to byte[] to do the app work.
I tried:
string ivStr = Encoding.Default.GetString(iv);
However when I tried to convert it back to a byte[] and then pass it back through to the decryption tool it would just fail and told me the length of the array was incorrect.
Any advice on this would be appreciated.

How to decrypt an OpenPGP RSA Encrypted text file in C#?

I am hoping that this question can be met with some guidance for someone who is beginning to work with encryption/decryption in C#. There are existing examples on the web regarding this, but I am truthfully struggling to put it all into practice for my given situation.
If given a text file that has been encrypted using OpenPGP with RSA, what is the best method to decrypt this in C#?
This is what I am attempting:
Using Kleopatra OpenPGP, I am generating a key pair using 2048bit RSA. This generates a private and public key.
I am then encrypting/signing a text file with a few word in it as a test.
In C#, I want to decrypt this text file.
Current code:
byte[] encryptedData = File.ReadAllBytes("C:\\PGP Encryption\\test.txt.gpg"); // The encrypted text file generated by Kleopatra.
using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
{
//Import the RSA Key information. This needs
//to include the private key information.
RSA.ImportParameters(RSAKeyInfo);
//Decrypt the passed byte array and specify OAEP padding.
decryptedData = RSA.Decrypt(DataToDecrypt, DoOAEPPadding);
}
return decryptedData;
Unfortunately, the RSA.Decrypt() call throws an exception that reads "The data to be decrypted exceeds the maximum for this modulus of 128 bytes."
I also do not believe that my private key is actually being loaded, as I'm not explicitly stating where the key is. But I don't see how the RSAParameters object is supposed to get populated otherwise.
If anyone can point me in the right direction to decrypt a file in this way, thank you in advance for your time and information.
It's looks like you need this library (see Decrypt section) https://github.com/mattosaurus/PgpCore

C# rsa decryption intermittent failure [duplicate]

This question already has an answer here:
RSA Encryption and Decryption successed in JS, but Decryption fails in C#
(1 answer)
Closed 3 years ago.
I have the following implementation for decrypting a value. This implementation works, but in some small case the values I'm attempting to decrypt are throwing a Cryptographic Exception, with the message 'The Parameter is incorrect'. This occurs where I call the Decrypt method on the private key below.
All values are encrypted with the public key, base64 encoded in transit, and passed along to this method the same way, so I don't understand why it would be blowing up sometimes. If I re-encrypt with the public key, that new value can usually be unencrypted successfully.
Certificate in this case below is the X509Certificate2
public string Decrypt(CertificateType certificateType, byte[] encryptedString)
{
string result = null;
var certificate = GetCertificate(certificateType);
var privateKey = certificate?.GetRSAPrivateKey();
if (privateKey != null)
{
var decryptedBytes = privateKey.Decrypt(encryptedString, RSAEncryptionPadding.Pkcs1);
result = Encoding.Default.GetString(decryptedBytes);
}
return result;
}
Any ideas as to what would cause that exception?
You should run it 1000x and log all the errors, see what those base64 input strings have in common and what the passing ones do - my guess is that it's padding related with the base64 encoding (Some encoders will pad with equal signs at the end of the strings and some won't, then some decoders expect the padding and some are able to handle it). When it lines up right, the decrypt works, when it doesn't (the length of the base64 string) the method throws an exception.
Other alternative is that instead of base64, you should be doing base64url encoding. When it works, it's because base64(x) == base64url(x) and when it doesn't it's because base64(x) != base64url(x)
Looks like it is with the Base64 encoding. Thank you for the help!
The Answer on this post did remove the decrypt issue I was having:
RSA Encryption and Decryption successed in JS, but Decryption fails in C#

Invalid length for a Base-64 char array

I trying to Decrypt password in visual studio 2010 using C-Sharp language but i m stuck on this error i try all the solution which was provided on this side but my error not resolved how i encrypt password can anybody tell me using MD5 my code is,Now it gives another error "String reference not set to an instance of a String.*Parameter name: s" What can i do i cant understand .I m newbie on C#*.I dont know what can i do if i waste your time then sorry to all.
public string PasswordDecrypt(string sQueryString)
{
byte[] buffer;
TripleDESCryptoServiceProvider loCryptoClass = new
TripleDESCryptoServiceProvider();
MD5CryptoServiceProvider loCryptoProvider = new MD5CryptoServiceProvider();
try
{
buffer = Convert.FromBase64String(sQueryString);
loCryptoClass.Key = loCryptoProvider.ComputeHash(ASCIIEncoding.ASCII.GetBytes(sQueryString));
loCryptoClass.IV = lbtVector;
return ASCIIEncoding.ASCII.GetString(loCryptoClass.CreateDecryptor().TransformFinalBlock(buffer, 0, buffer.Length));
}
catch (Exception ex)
{
throw ex;
}
finally
{
loCryptoClass.Clear();
loCryptoProvider.Clear();
loCryptoClass = null;
loCryptoProvider = null;
}
}
The code relevant to your question is this:
string sQueryString = txtPassword.Text;
byte[] buffer = Convert.FromBase64String(sQueryString);
Create a test case for this, containing the data as is entered when you get the error. Perhaps your users don't input their password as base64.
I think you are confused about what to do for password security. Passwords don't get encrypted, they get hashed. That's kind of a one-way-encryption. The same password will always result in the same hash, but different passwords are allowed to generate the same hash, so it's impossible to decrypt it from hash to password.
While that doesn't sound useful at first, the point is that you never actually store the password, encrypted or not. You store the hash value of the password. That way you know when someone enters a password, it gets hashed and matches the stored hash, it's the correct password... without ever knowing what the password was.
So you cannot decrypt a hash. You simply hash your input and compare with an earlier hash from the correct password.
Please note that you should also google Salting hashes, a technique for lowering the attack surface of hashes once the data store was breached and the hash is known to potential attackers.

AES file encryption with .Net Framework and decrypt it with IOS

We encrypt PDFs using AESManaged algorithm implemented in .NET framework. I used the example explained in here to implement C# code to encrypt the file. Now I need to decrypt that file using an iPhone application.(That is the requirement). So I use the this code to do that but decryption failed by returning an error.
'Error Domain=CommonCryptoErrorDomain Code=-4304 "Decode Error"
UserInfo=0x127356c0 {NSLocalizedFailureReason=Input data did not
decode or decrypt correctly, NSLocalizedDescription=Decode Error'
Can some one help me to resolve this issue.
We use 12345678 as encryption key.
Most likely the problem is in the deriving actual key from the password (12345678 cannot be the AES key directly - it is only 8 bytes).
Technically this should work though I've never tested it, both methods uses the same ad-hoc format.
Encrypt using my authenticated encryption example.
//use your secret data you want to encrypt instead.
String secretMessage = "Message";
var rnCryptorHeader = new Byte[]{
2, //RNCryptor Format version 2
0 //RNCryptor Uses password
};
//encryptedString is base64 encoded
var encryptedString = AESThenHMAC.SimpleEncryptWithPassword(secretMessage,
password:"1234567891011",
nonSecretPayload:rnCryptorHeader);
Then Decrypt using RNCryptor and NSData+Base64 for IOS
//This is the encrypted data passed from .net
NSString *encryptedString = #"AgE8C9E7gsfyOAmSotIOgyLQ0O6mdcuMXXjN/iZa3azym4KVWZAkfykIP6mqMt/qkpfftdB3XQhMkoxtQEM+rA0iHxOvZiNlmA2KJtg6BOnmlg==";
NSData *encryptedData = [NSData dataFromBase64String: encryptedString];
NSError *error;
NSData *decryptedData = [RNDecryptor decryptData:encryptedData
withPassword:#"1234567891011"
error:&error];
NSString *secretMessage = [[[NSString alloc] initWithData:decryptedData
encoding:NSUTF8StringEncoding] autorelease];
Since you aren't dealing with strings and are dealing with bytes directly, just remove the Base64 and utf8 encoding/decoding from this objective-c example and the linked c# example, once you are sure this is working.

Categories

Resources