I am trying to compute the sha1 of a file using the below method. The result is different from what is reported by "git ls-tree HEAD". What's wrong with my code?
static public string ComputeSha1()
{
//"blob " + <size_of_file> + "\0" + <contents_of_file>
var content = File.ReadAllBytes(#"c:\projects\myproj\Word.docx");
var contentLength = Encoding.UTF8.GetByteCount(Encoding.UTF8.GetString(content));
var blob = "blob " + contentLength + "\0" + Encoding.UTF8.GetString(content);
using (SHA1 sha1 = SHA1.Create())
{
byte[] bytes = sha1.ComputeHash(Encoding.UTF8.GetBytes(blob));
StringBuilder builder = new StringBuilder();
for (int i = 0; i < bytes.Length; i++)
{
builder.Append(bytes[i].ToString("x2"));
}
return builder.ToString();
}
}
Related
How to integrate Payumoney payment gateway using backend- Aspnetcore and Frontend - React js? Kindly help me
[HttpPost("onlinePayment")]
[EnableCors("CorsPolicy")]
public void onlinePayment()
{
string merchantKey = "*******";
string salt = "*******";
byte[] hash;
Random rnd = new Random();
string hex = "";
string text = hex + rnd.ToString() + DateTime.Now;
byte[] message = Encoding.UTF8.GetBytes(text);
UnicodeEncoding UE = new UnicodeEncoding();
byte[] hashValue;
SHA512Managed hashString = new SHA512Managed();
hashValue = hashString.ComputeHash(message);
foreach (byte x in hashValue)
{
hex += String.Format("{0:x2}", x);
}
string strHash = hex;
string txnid1 = strHash.ToString().Substring(0, 20);
string d = merchantKey+"|"+ txnid1+"|"+ 1000 + "|" + "TestInfo" + "|" + "Dhana" + "|" + "dhana#gmail.com"+"|||||"+ salt;
var datab = Encoding.UTF8.GetBytes(d);
using (SHA512 shaM = new SHA512Managed())
{
hash = shaM.ComputeHash(datab);
}
Response.Redirect("https://test.payu.in/_payment");
Response.Headers.Add("Access-Control-Allow-Origin", "*");
Response.Headers.Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
return;
}
This is backend code i am trying to integrate with js..It is correct way to integrate or not?
Or give me some code examples.
I used this code to decode bytes sent from the server
packets = SimpleBSON.Load(ReceivedBytes);
for (int i = 0; i < packets["mc"]; i++)
{
BSONObject packet = packets["m" + i] as BSONObject;
//here i can use the received packet
packet["hey"] = "hello";
}
But I am struggling in encoding it back again
I am using Kernys.BSON
I tried this
var obj = new BSONObject();
obj["m" + 0] = new BSONObject();
obj["m" + 0]["hey"] = "hi";
But for some reason this is not working
this is how I fixed it
var GPd = new BSONObject();
GPd["m" + 0] = new BSONObject();
GPd["m" + 0]["hey"] = "hi";
GPd["mc"] = 1;
byte[] mainsend = SimpleBSON.Dump(GPd);
MemoryStream memoryStream = new MemoryStream();
using (BinaryWriter binaryWriter = new BinaryWriter(memoryStream))
{
byte[] bsonDump = SimpleBSON.Dump(GPd);
binaryWriter.Write(bsonDump.Length + 4);
binaryWriter.Write(bsonDump);
}
//memorystream.ToArray is the encoded bytes
}
I have a encryption example from a 3rd party i need to integrate with ...
I am supposed to send them encrypted message and they does decrypt it on their end and performs needed operations.
They have provided me the example that's how they are expecting the string to be encrypted ..
echo -n ['String to encrypt'] | openssl enc -aes-128-cbc -A -a -nosalt -K [EncryptionKey in Hex] -iv 30303030303030303030303030303030
The sandbox encryptionKey Hex that i am given with is 313233343536373839
Currently i am not able to use above specified key and IV as is ... as the AES implementations in .Net throws me and error which says 'The specified key is not a Valid size for this algorithm'
then i just padded the key with 0s to match 32 bytes and truncated the IV to match 16 bytes..
then i am able to run the code atleast but the encrypted string from my c# code just couldn't get decrypted on openssl ..
Below is my code ..
public static string EncryptString(string plainText, string password)
{
byte[] key, iv;
//converting key to hex
byte[] ba = Encoding.ASCII.GetBytes("0123456789abcdef");
string encryptionKeyHex = BitConverter.ToString(ba);
encryptionKeyHex = encryptionKeyHex.Replace("-", "");
// Padding key hex with zeros to match the size that .Net algo expects
if (encryptionKeyHex.Length < 32)
{
while (encryptionKeyHex.Length < 32)
{
encryptionKeyHex += "0";
}
}
var keyBytes = Encoding.ASCII.GetBytes(encryptionKeyHex);
var ivBytes = Encoding.ASCII.GetBytes("3030303030303030"); // truncated the original IV specified in the question description to match the size.
iv = ivBytes;
key = keyBytes;
var amAes = new AesManaged();
amAes.Mode = CipherMode.CBC;
amAes.Padding = PaddingMode.PKCS7;
amAes.KeySize = 128;
amAes.BlockSize = 128;
amAes.Key = key;
amAes.IV = iv;
var icTransformer = amAes.CreateEncryptor();
var msTemp = new MemoryStream();
var csEncrypt = new CryptoStream(msTemp, icTransformer, CryptoStreamMode.Write);
var sw = new StreamWriter(csEncrypt);
sw.Write(plainText);
sw.Close();
sw.Dispose();
csEncrypt.Clear();
csEncrypt.Dispose();
byte[] bResult = msTemp.ToArray();
//var sha = new SHA1CryptoServiceProvider();
//var result = sha.ComputeHash(bResult);
string sResult = Convert.ToBase64String(bResult);
sResult = HttpUtility.UrlEncode(sResult);
if (System.Diagnostics.Debugger.IsAttached)
{
string debugDetails = "";
debugDetails += "==> INPUT : " + plainText + Environment.NewLine;
debugDetails += "==> SECRET : " + password + Environment.NewLine;
//debugDetails += "==> SALT : " + Program.ByteArrayToHexString(salt) + Environment.NewLine;
debugDetails += "==> KEY : " + Encoding.ASCII.GetString(amAes.Key) + " (" + amAes.KeySize.ToString() + ")" + Environment.NewLine;
debugDetails += "==> IV : " + Encoding.ASCII.GetString(amAes.IV) + Environment.NewLine;
debugDetails += "==> ENCRYPTED : " + sResult;
Console.WriteLine(debugDetails);
}
return sResult;
}
OUTPUT:
==> INPUT : {"filter.accession_number.equals":"0987654321"}
==> SECRET :
==> KEY : 30313233343536373839000000000000 (256)
==> IV : 3030303030303030
==> ENCRYPTED : B2uDRjnekFAlRDEKDldTs09lWiE4u16ZunVwDGi6gKm6YsaRlW4HU6eKJqfYZc7b
Update
It has been noticed that we get different results when encrypting on a windows box than on a Linux Box, using the same method ..
On linux box using openssl we get ..
The command:
echo -n '{"filter.accession_number.equals":"0987654321"}' | openssl enc -aes-128-cbc -A -a -nosalt -K 313233343536373839 -iv 30303030303030303030303030303030
The Result:
MTAusb6rYkxYf9/REbFq9M1XwR+6Q58FfSJPTxDNwgs6z3jZ8ru+7ysnKuy2p3ox
That encrypted string works just fine .. i am able to decrypt it successfully.
While issuing the same command on windows box to openssl gives us ..
The command:
echo -n '{"filter.accession_number.equals":"0987654321"}' | openssl enc -aes-128-cbc -A -a -nosalt -K 313233343536373839 -iv 30303030303030303030303030303030
The Result:
Db9829q6QX6CPwLkE+rs6zqRJJQaGZ9xk7fbztaGqsKcHPcr7equz3yOJPLc+S6yvW4jXQTzoOk43F16GW7sPw==
This string doesn't work ...
You're simply forgetting to decode the hexadecimals; Encoding.ASCII.GetBytes only gets the ASCII representation of the key and IV.
Check the answer here to convert correctly to bytes (i.e. replace Encoding.ASCII.GetBytes with StringToByteArray).
Here is the working code sample for anyone who gets stuck in to similar problem...
#Maarten Bodewes You did point me in the right direction, just had to re-arrange the code to make it work. Thanks :)
public static string EncryptString(string plainText)
{
byte[] key, iv;
byte[] rawKey = Encoding.ASCII.GetBytes("123456789abcdef");
string encryptionKeyHex = BitConverter.ToString(rawKey);
byte[] hexKayBytes = FromHex(encryptionKeyHex); // convert to bytes with 'dashes'
byte[] data = FromHex("30-30-30-30-30-30-30-30-30-30-30-30-30-30-30-30");
encryptionKeyHex = ByteArrayToHexString(hexKayBytes);
// modifying key size to match the algorithm validation on key size
if (encryptionKeyHex.Length < 32)
{
while (encryptionKeyHex.Length < 32)
{
encryptionKeyHex += "0";
}
}
var ivOriginal = BitConverter.ToString(data);
ivOriginal = ivOriginal.Replace("-", "");
if (ivOriginal.Length < 16)
{
while (ivOriginal.Length < 16)
{
ivOriginal += "0";
}
}
var keyBytes = StringToByteArray(encryptionKeyHex);
var ivBytes = StringToByteArray(ivOriginal);
iv = ivBytes;
key = keyBytes;
var amAes = new AesManaged();
amAes.Mode = CipherMode.CBC;
amAes.Padding = PaddingMode.PKCS7;
amAes.KeySize = 128;
amAes.BlockSize = 128;
amAes.Key = key;
amAes.IV = iv;
var icTransformer = amAes.CreateEncryptor();
var msTemp = new MemoryStream();
var csEncrypt = new CryptoStream(msTemp, icTransformer, CryptoStreamMode.Write);
var sw = new StreamWriter(csEncrypt);
sw.Write(plainText);
sw.Close();
sw.Dispose();
csEncrypt.Clear();
csEncrypt.Dispose();
byte[] bResult = msTemp.ToArray();
string sResult = Convert.ToBase64String(bResult);
if (System.Diagnostics.Debugger.IsAttached)
{
string debugDetails = "";
debugDetails += "==> INPUT : " + plainText + Environment.NewLine;
debugDetails += "==> SECRET : " + password + Environment.NewLine;
//debugDetails += "==> SALT : " + Program.ByteArrayToHexString(salt) + Environment.NewLine;
debugDetails += "==> KEY : " + Encoding.ASCII.GetString(amAes.Key) + " (" + amAes.KeySize.ToString() + ")" + Environment.NewLine;
debugDetails += "==> IV : " + Encoding.ASCII.GetString(amAes.IV) + Environment.NewLine;
debugDetails += "==> ENCRYPTED : " + sResult;
Console.WriteLine(debugDetails);
}
return sResult;
}
public static byte[] FromHex(string hex)
{
hex = hex.Replace("-", "");
byte[] raw = new byte[hex.Length / 2];
for (int i = 0; i < raw.Length; i++)
{
raw[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
}
return raw;
}
private static string ByteArrayToHexString(byte[] bytes)
{
StringBuilder sbHex = new StringBuilder();
foreach (byte b in bytes)
sbHex.AppendFormat("{0:x2}", b);
return sbHex.ToString();
}
public static byte[] StringToByteArray(String hex)
{
int NumberChars = hex.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
return bytes;
}
I use RSA cryptography to Enc/Dec message
Encryption is work well but when Decrypting I got This error on this line .
rsa.Decrypt(dataByte, false);
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Security.Cryptography.CryptographicException: The parameter is incorrect.
code is:
string en= x509_Encrypt(Current_Record_Hmac, PFXFile, s_pass);
string de= ByteToString( X509_Decrypt(en, PFXFile, s_pass));
public static byte[] X509_Decrypt(string data, string certificateFile, string password)
{
var dataArray = data.Split(new char[] { ',' });
byte[] dataByte = new byte[dataArray.Length];
for (int i = 0; i < dataArray.Length; i++)
{
dataByte[i] = Convert.ToByte(dataArray[i]);
}
X509Certificate2 cert = new X509Certificate2(certificateFile, password);
var rsa = new RSACryptoServiceProvider();
var x509_privateKey = cert.PrivateKey;
string pri = x509_privateKey.ToString();
string x509_privateKey_ToString = x509_privateKey.ToString();
string X509_publicKey = ByteToString(cert.GetPublicKey());
x509_privateKey_ToString = rsa.ToXmlString(true);
X509_publicKey = rsa.ToXmlString(false);
rsa.FromXmlString(x509_privateKey_ToString);
var decryptedByte = rsa.Decrypt(dataByte, false);
return (decryptedByte);
}
public string x509_Encrypt(string input, string certificateFile, string password)
{
var dataToEncrypt = _encoder.GetBytes(input);
var encoding = new System.Text.ASCIIEncoding();
X509Certificate2 cert = new X509Certificate2(certificateFile, password);
var x509_privateKey = cert.PrivateKey;
string x509_privateKey_ToString = ByteToString(encoding.GetBytes(x509_privateKey.ToString()));
string X509_publicKey = ByteToString(cert.GetPublicKey());
//Encrypting the text using the public key
RSACryptoServiceProvider cipher = new RSACryptoServiceProvider();
x509_privateKey_ToString = cipher.ToXmlString(true);
X509_publicKey = cipher.ToXmlString(false);
cipher.FromXmlString(X509_publicKey);
var encryptedByteArray = cipher.Encrypt(dataToEncrypt, false).ToArray();
var length = encryptedByteArray.Count();
var item = 0;
var sb = new StringBuilder();
foreach (var x in encryptedByteArray)
{
item++;
sb.Append(x);
if (item < length)
sb.Append(",");
}
return sb.ToString();
}
Try this for your decrypt method:
public string X509_Decrypt(string inputString, string pathToCertFile, string password)
{
if (inputString == null)
{
return null;
}
X509Certificate2 certificate = new X509Certificate2(pathToCertFile, password, X509KeyStorageFlags.MachineKeySet);
try
{
var cryptoProvider = (RSACryptoServiceProvider)certificate.PrivateKey;
int dwKeySize = cryptoProvider.KeySize;
int blockSize = ((dwKeySize / 8) % 3 != 0) ? (((dwKeySize / 8) / 3) * 4) + 4 : ((dwKeySize / 8) / 3) * 4;
int iterations = inputString.Length / blockSize;
var arrayList = new ArrayList();
for (int i = 0; i < iterations; i++)
{
byte[] encryptedBytes = Convert.FromBase64String(
inputString.Substring(blockSize * i, blockSize));
Array.Reverse(encryptedBytes);
arrayList.AddRange(cryptoProvider.Decrypt(encryptedBytes, true));
}
return Encoding.UTF32.GetString(arrayList.ToArray(Type.GetType("System.Byte")) as byte[]);
}
catch (Exception ex)
{
throw new SystemException(ex.Message);
}
}
And try this for your encrypt message:
public string X509_Encrypt(string inputString, string pathToCertFile, string password)
{
if (inputString == null)
{
return null;
}
X509Certificate2 certificate = new X509Certificate2(pathToCertFile, password, X509KeyStorageFlags.MachineKeySet);
try
{
// TODO: Add Proper Exception Handlers
var rsaCryptoServiceProvider = (RSACryptoServiceProvider)certificate.PublicKey.Key;
int keySize = rsaCryptoServiceProvider.KeySize / 8;
byte[] bytes = Encoding.UTF32.GetBytes(inputString);
int maxLength = keySize - 42;
int dataLength = bytes.Length;
int iterations = dataLength / maxLength;
var stringBuilder = new StringBuilder();
for (int i = 0; i <= iterations; i++)
{
var tempBytes = new byte[ (dataLength - maxLength * i > maxLength) ? maxLength : dataLength - maxLength * i];
Buffer.BlockCopy(bytes, maxLength * i, tempBytes, 0, tempBytes.Length);
byte[] encryptedBytes = rsaCryptoServiceProvider.Encrypt(tempBytes, true);
Array.Reverse(encryptedBytes);
stringBuilder.Append(Convert.ToBase64String(encryptedBytes));
}
return stringBuilder.ToString();
}
catch (Exception ex)
{
throw new SystemException(ex.Message);
}
}
You cannot just convert bytes to characters like that. If you want to transmit the ciphertext as a string you need to use an encoding such as base 64 encoding and decode before decryption.
I am trying to develop an app that will upload large files to a web server running PHP. Almost immediately, I stumbled upon a problem that the file is not split correctly.
Currently I have this piece of code
string adrese = "c:\\directory\\file.jpg";
int garums = 16384;
String ext = Path.GetExtension(adrese);
FileStream file = /*/File.Open(adrese, FileMode.Open);/*/
new FileStream(adrese, FileMode.Open, System.IO.FileAccess.Read);
long fgar = file.Length; //100%
long counter = garums;
first = true;
byte[] chunk = new byte[garums];
while (true)
{
int index = 0;
//long Controll = counter+garums;
while (index < chunk.Length)
{
int bytesRead = file.Read(chunk, index, chunk.Length - index);
if (bytesRead == 0)
{
/*byte[] biti = new byte[index];
for (int i = 0; i < index; i++)
{
biti[i] = chunk[i];
}
chunk = new byte[index];
chunk = biti;*/
break;
}
index += bytesRead;
}
if (index != 0) // Our previous chunk may have been the last one
{
byte[] biti = new byte[index];
for (int i = 0; i < index; i++)
{
biti[i] = chunk[i];
}
chunk = new byte[index];
chunk = biti;
// index is the number of bytes in the chunk
sutam(Convert.ToBase64String(chunk),ext);
}
double procentuali = ((counter * 100) / fgar);
if (procentuali > 99)
{
procentuali = 100;
}
progressBar1.Value = (int)Math.Round(procentuali);
label1.Text = "" + procentuali;
counter = counter+garums;
if (index != garums) // We didn't read a full chunk: we're done
{
return;
}
}
file.Close();
Everything works if I set garums to 1, but who will wait for a year or so to upload a file sized multiple GB's.
I would be pleased if you could tell me what is wrong and how to fix this.
Try this instead to upload in chunks:
private void ConvertToChunks()
{
//Open file
string file = MapPath("~/temp/1.xps");
FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
//Chunk size that will be sent to Server
int chunkSize = 1024;
// Unique file name
string fileName = Guid.NewGuid() + Path.GetExtension(file);
int totalChunks = (int)Math.Ceiling((double)fileStream.Length / chunkSize);
// Loop through the whole stream and send it chunk by chunk;
for (int i = 0; i < totalChunks; i++)
{
int startIndex = i * chunkSize;
int endIndex = (int)(startIndex + chunkSize > fileStream.Length ? fileStream.Length : startIndex + chunkSize);
int length = endIndex - startIndex;
byte[] bytes = new byte[length];
fileStream.Read(bytes, 0, bytes.Length);
ChunkRequest(fileName, bytes);
}
}
private void ChunkRequest(string fileName,byte[] buffer)
{
//Request url, Method=post Length and data.
string requestURL = "http://localhost:63654/hello.ashx";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestURL);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
// Chunk(buffer) is converted to Base64 string that will be convert to Bytes on the handler.
string requestParameters = #"fileName=" + fileName + "&data=" + HttpUtility.UrlEncode( Convert.ToBase64String(buffer) );
// finally whole request will be converted to bytes that will be transferred to HttpHandler
byte[] byteData = Encoding.UTF8.GetBytes(requestParameters);
request.ContentLength = byteData.Length;
Stream writer = request.GetRequestStream();
writer.Write(byteData, 0, byteData.Length);
writer.Close();
// here we will receive the response from HttpHandler
StreamReader stIn = new StreamReader(request.GetResponse().GetResponseStream());
string strResponse = stIn.ReadToEnd();
stIn.Close();
}