public static EncryptedFile encryptDataForSharedFile(byte[] inputBytes, X509Certificate2 targetUserCertificate) { byte[] encryptedData_DsCombo; byte[] symmetricKey; TripleDESCng des = new TripleDESCng(); symmetricKey = des.Key; var cer = File.ReadAllText((Application.Current.Properties["userCertificateLocation"].ToString())); var eccPem = File.ReadAllText(Application.Current.Properties["userPrivateKeyLocation"].ToString()); var cert = X509Certificate2.CreateFromPem(cer, eccPem); //digital signature, hash of the original document, encrypted by users private key RSACng rsa = (RSACng)cert.GetRSAPrivateKey(); byte[] signedHash = rsa.SignData(inputBytes, HashAlgorithmName.SHA384, RSASignaturePadding.Pkcs1); //data + digitalsignature (sha384 - 384bits) byte[] data_ds_combo = combine(inputBytes, signedHash); encryptedData_DsCombo = encryptBytes(des, data_ds_combo); //[data + digital signature] byte[] keyEncrypted = encryptBytesPublicKey(symmetricKey, targetUserCertificate);//userCertificate); EncryptedFile outFile = new EncryptedFile(encryptedData_DsCombo, keyEncrypted, des.IV); //initialize sender, so we know whose certificate to use for data verification outFile.setSender(Encoding.UTF8.GetBytes(Application.Current.Properties["Username"].ToString())); return(outFile); }
public static byte[] decryptSharedFile(EncryptedFile encryptedFile, X509Certificate2 senderCertificate) { TripleDESCng aes = new TripleDESCng(); var cer = File.ReadAllText((Application.Current.Properties["userCertificateLocation"].ToString())); var eccPem = File.ReadAllText(Application.Current.Properties["userPrivateKeyLocation"].ToString()); var cert = X509Certificate2.CreateFromPem(cer, eccPem); //separate from input data byte[] encryptedKey = encryptedFile.getKey(); byte[] decryptedKey = decryptBytesPrivateKey(encryptedKey, cert); byte[] encryptedData_DsCombo = encryptedFile.getData(); //feed the aes class with the needed parameters aes.IV = encryptedFile.getIV(); aes.Key = decryptedKey; byte[] decryptedData_DsCombo = decryptBytes(aes, encryptedData_DsCombo); //sha256 signature takes 256bytes from the end byte[] signedHash = decryptedData_DsCombo.TakeLast(256).ToArray(); byte[] data = decryptedData_DsCombo.Take(decryptedData_DsCombo.Length - 256).ToArray(); RSACng rsa = (RSACng)senderCertificate.GetRSAPublicKey(); if (rsa.VerifyData(data, signedHash, HashAlgorithmName.SHA384, RSASignaturePadding.Pkcs1)) { return(data); } else { //dignuti upozorenje iznad //MessageBox.Show("File corrupted!"); throw new CryptographicException("File corrupted"); } }