What is the length of ciphertext for AES encryption using C#? - encryption

From:
Can we calculate AES ciphertext length based on the length of the plaintext?
I see: output_size = input_size + (16 - (input_size % 16))
But this does not seem to correspond with what I see when running tests using C# and the AesCng with PKCS7 padding and CBC CipherMode.
Thoughts on how I calculate the length of the encrypted value?
Here's the code for sample program:
Public Shared Function Encrypt(ByVal plainText As String, ByVal aes256BitKeyValue As String, ByVal initialVector As String) As String
If String.IsNullOrEmpty(plainText) Then
Return String.Empty
End If
Dim initialVectorBytes As Byte() = System.Text.Encoding.ASCII.GetBytes(initialVector)
Dim plainTextBytes As Byte() = System.Text.Encoding.UTF8.GetBytes(plainText)
Dim cipherTextBytes As Byte() = Nothing
Using symmetricKey As New System.Security.Cryptography.AesCng()
symmetricKey.Padding = Security.Cryptography.PaddingMode.PKCS7
symmetricKey.Mode = System.Security.Cryptography.CipherMode.CBC
Dim keyBytes As Byte() = StringToByteArray(aes256BitKeyValue)
Try
Using cryptographyTransform As System.Security.Cryptography.ICryptoTransform = symmetricKey.CreateEncryptor(keyBytes, initialVectorBytes)
Using memoryStream As New System.IO.MemoryStream()
Using cryptographyStream As New System.Security.Cryptography.CryptoStream(memoryStream, cryptographyTransform, System.Security.Cryptography.CryptoStreamMode.Write)
cryptographyStream.Write(plainTextBytes, 0, plainTextBytes.Length)
cryptographyStream.FlushFinalBlock()
cipherTextBytes = memoryStream.ToArray()
memoryStream.Close()
cryptographyStream.Close()
End Using
End Using
End Using
Catch ex As Exception
Throw New Exceptions.EncryptionException(String.Format(System.Globalization.CultureInfo.InvariantCulture, Resources.ExceptionMessages.EncryptionFailed1, ex))
Finally
symmetricKey.Clear()
End Try
End Using
Return Convert.ToBase64String(cipherTextBytes)
End Function
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string aes256Key = "1234567890123456789012345678901234567890123456789012345678901234";
string initialVector = "66sDeG*3xsS334dE";
string unencrypted20Text = "12345678901234567890";
string unencrypted40Text = "1234567890123456789012345678901234567890";
string unencrypted64Text = "1234567890123456789012345678901234567890123456789012345678901234";
string unencrypted128Text = "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678";
string unencrypted256Text = "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456";
string unencrypted257Text = "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567";
string unencrypted512Text = unencrypted256Text + unencrypted256Text;
string unencrypted1024Text = unencrypted512Text + unencrypted512Text;
string unencrypted2048Text = unencrypted1024Text + unencrypted1024Text;
string unencrypted4096Text = unencrypted2048Text + unencrypted2048Text;
string unencrypted8192Text = unencrypted4096Text + unencrypted4096Text;
string encrypted20Text = Grb.Core.Cryptography.AesEncryption.Encrypt(unencrypted20Text, aes256Key, initialVector);
string encrypted40Text = Grb.Core.Cryptography.AesEncryption.Encrypt(unencrypted40Text, aes256Key, initialVector);
string encrypted64Text = Grb.Core.Cryptography.AesEncryption.Encrypt(unencrypted64Text, aes256Key, initialVector);
string encrypted128Text = Grb.Core.Cryptography.AesEncryption.Encrypt(unencrypted128Text, aes256Key, initialVector);
string encrypted256Text = Grb.Core.Cryptography.AesEncryption.Encrypt(unencrypted256Text, aes256Key, initialVector);
string encrypted257Text = Grb.Core.Cryptography.AesEncryption.Encrypt(unencrypted257Text, aes256Key, initialVector);
string encrypted512Text = Grb.Core.Cryptography.AesEncryption.Encrypt(unencrypted512Text, aes256Key, initialVector);
string encrypted1024Text = Grb.Core.Cryptography.AesEncryption.Encrypt(unencrypted1024Text, aes256Key, initialVector);
string encrypted2048Text = Grb.Core.Cryptography.AesEncryption.Encrypt(unencrypted2048Text, aes256Key, initialVector);
string encrypted4096Text = Grb.Core.Cryptography.AesEncryption.Encrypt(unencrypted4096Text, aes256Key, initialVector);
string encrypted8192Text = Grb.Core.Cryptography.AesEncryption.Encrypt(unencrypted8192Text, aes256Key, initialVector);
int encrypted20TextLength = encrypted20Text.Length; // actual: 44, expected 20 + (16 - 4) = 32
int encrypted40TextLength = encrypted40Text.Length; // actual: 64, expected 40 + (116 - 8) = 48
int encrypted64TextLength = encrypted64Text.Length; // actual: 108, expected 64 + (16 - 0) = 80
int encrypted128TextLength = encrypted128Text.Length; // actual: 192, expected 128 + (16 - 0) = 144
int encrypted256TextLength = encrypted256Text.Length; // actual: 364
int encrypted257TextLength = encrypted257Text.Length; // actual: 364
int encrypted512TextLength = encrypted512Text.Length; // actual: 704
int encrypted1024TextLength = encrypted1024Text.Length; // actual: 1388
int encrypted2048TextLength = encrypted2048Text.Length; // actual: 2752
int encrypted4096TextLength = encrypted4096Text.Length; // actual: 5484
int encrypted8192TextLength = encrypted8192Text.Length; // actual: 10944
}
}
}

Related

Cannot implicitly convert type object to microsoft.Office.Interop.Excel.Worksheet, an explicit conversion exists

public void ExportToexcel(DataSet ds , string strpath)
{
int inheaderleghth = 3, incliomn = 0, inrow = 0;
System.Reflection.Missing Default = System.Reflection.Missing.Value;
strpath += #"";
excel.Application exceApp = new excel.Application();
excel.Workbook excelWorkBook = exceApp.Workbooks.Add(1);
foreach(DataTable dtbl in ds.Tables)
{
//error show below line
excel.Worksheet ecxelworksheet = excelWorkBook.Sheets.Add(Type.Missing, excelWorkBook.Sheets[excelWorkBook.Sheets.Count],1,Default);
}
}
Use a soft cast, i.e.,
excel.Worksheet ecxelworksheet = excelWorkBook.Sheets.Add(
Type.Missing,
excelWorkBook.Sheets[excelWorkBook.Sheets.Count],
1,Default) as excel.Worksheet;

Cutting and saving video in folder using ffmpeg

private bool ReturnVideo(string fileName)
{
string html = string.Empty;
//rename if file already exists
int j = 0;
string AppPath;
string inputPath;
string outputPath;
// string imgpath;
AppPath = Request.PhysicalApplicationPath;
//Get the application path
inputPath = AppPath + "OriginalVideo";
//Path of the original file
outputPath = AppPath + "ConvertVideo";
//Path of the converted file
// imgpath = AppPath + "Thumbs";
//Path of the preview file
string filepath = Server.MapPath("~/OriginalVideo/" + fileName);
while (File.Exists(filepath))
{
j = j + 1;
int dotPos = fileName.LastIndexOf(".");
string namewithoutext = fileName.Substring(0, dotPos);
string ext = fileName.Substring(dotPos + 1);
fileName = namewithoutext + j + "." + ext;
filepath = Server.MapPath("~/OriginalVideo/" + fileName);
}
try
{
this.fileuploadImageVideo.SaveAs(filepath);
}
catch
{
// return false;
}
string outPutFile;
outPutFile = "~/OriginalVideo/" + fileName;
int i = this.fileuploadImageVideo.PostedFile.ContentLength;
System.IO.FileInfo a = new System.IO.FileInfo(Server.MapPath(outPutFile));
string cmd = "-y -ss 00:00:00 -to 00:00:10 -i " + inputPath + "\\" + fileName + " -vcodec copy -acodec copy " + outputPath + "\\" + fileName.Remove(fileName.IndexOf(".")) + ".mp4";
ConvertNow(cmd);
return true;
}
private void ConvertNow(string cmd)
{
string exepath;
string AppPath = Request.PhysicalApplicationPath;
//Get the application path
exepath = AppPath + "ffmpeg\\ffmpeg.exe";
Process proc = new Process();
proc.StartInfo.FileName = exepath;
//Path of exe that will be executed, only for "filebuffer" it will be "flvtool2.exe"
proc.StartInfo.Arguments = cmd;
//The command which will be executed
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.RedirectStandardOutput = false;
proc.Start();
//while (proc.HasExited == false)
//{
//}
}

How to call a function with struct as input?

Here is my struct definition, function and the portion calling the function.
public struct NewSigningRequest
{
public string SerialNumber;
//public string Requestor;
public string Sponsor;
public string Approver;
public string BusinessJustification;
public byte[] DebugFile;
public string DebugFileName;
public string FirmwareVersion;
public string FirmwareDescription;
public byte[] SmokeTestResult;
public string ProductName;
public string SigningType;
}
static public bool CreateSigningRequest(NewSigningRequest Request)
{
Request = new NewSigningRequest();
bool succeeded = false;
string sqlcmdString = sqlQueryNewSigningRequest;
SqlConnection con = new SqlConnection(connection);
SqlCommand Insertcmd = new SqlCommand(sqlcmdString, con);
SqlParameter SerialNumber = new SqlParameter("#SerialNumber", SqlDbType.NVarChar, 50);
SerialNumber.Value = Request.SerialNumber;
Insertcmd.Parameters.Add(SerialNumber);
SqlParameter Requestor = new SqlParameter("#Requestor", SqlDbType.NVarChar, 20);
Requestor.Value = GetRequestor.GetRequestorAlias();
Insertcmd.Parameters.Add(Requestor);
SqlParameter Sponsor = new SqlParameter("#Sponsor", SqlDbType.NVarChar, 20);
Sponsor.Value = Request.Sponsor;
Insertcmd.Parameters.Add(Sponsor);
SqlParameter BusinessJustification = new SqlParameter("#BusinessJustification", SqlDbType.NVarChar, 2000);
BusinessJustification.Value = Request.BusinessJustification;
Insertcmd.Parameters.Add(BusinessJustification);
SqlParameter DebugFile = new SqlParameter("#DebugFile", SqlDbType.VarBinary, 8000);
DebugFile.Value = Request.DebugFile;
Insertcmd.Parameters.Add(DebugFile);
SqlParameter DebugFileName = new SqlParameter("#DebugFileName", SqlDbType.NVarChar, 100);
DebugFileName.Value = Request.DebugFileName;
Insertcmd.Parameters.Add(DebugFileName);
SqlParameter ProductName = new SqlParameter("#ProductName", SqlDbType.NVarChar, 20);
ProductName.Value = Request.ProductName;
Insertcmd.Parameters.Add(ProductName);
SqlParameter SigningType = new SqlParameter("#SigningType", SqlDbType.NVarChar, 10);
SigningType.Value = Request.SigningType;
Insertcmd.Parameters.Add(SigningType);
SqlParameter FirmwareVersion = new SqlParameter("#FirmwareVersion", SqlDbType.NVarChar, 50);
FirmwareVersion.Value = Request.FirmwareVersion;
Insertcmd.Parameters.Add(FirmwareVersion);
SqlParameter FirmwareDescription = new SqlParameter("#FirmwareDescription", SqlDbType.NVarChar, 250);
FirmwareDescription.Value = Request.FirmwareDescription;
Insertcmd.Parameters.Add(FirmwareDescription);
SqlParameter SmokeTestResult = new SqlParameter("#SmokeTestResult", SqlDbType.VarBinary, 8000);
SmokeTestResult.Value = Request.SmokeTestResult;
Insertcmd.Parameters.Add(SmokeTestResult);
return succeeded;
}
this is how I am trying to call it
NewSigningRequest Request;
byte[] bin;
string FileName;
if (FileUpload.HasFile)
{
bin = new byte[FileUpload.PostedFile.ContentLength];
HttpPostedFile mybin = FileUpload.PostedFile;
FileName = mybin.FileName;
mybin.InputStream.Read(bin, 0, FileUpload.PostedFile.ContentLength);
}
else
{
bin = null;
FileName = "";
}
string NameAlias = #HttpContext.Current.User.Identity.Name;
int index = NameAlias.IndexOf("\\") + 1;
string sAlias = NameAlias.Substring(index);
byte[] SmokeTest;
if (FileUploadSTR.HasFile)
{
SmokeTest = new byte[FileUploadSTR.PostedFile.ContentLength];
HttpPostedFile mySmokeTest = FileUploadSTR.PostedFile;
mySmokeTest.InputStream.Read(SmokeTest, 0, FileUploadSTR.PostedFile.ContentLength);
}
else
{
SmokeTest = null;
}
Request.SerialNumber = TextBoxSerialNumber.Text;
Request.Sponsor = TextBoxSponsor.Text;
Request.BusinessJustification = TextBoxBJ.Text;
if (bin == null)
{
Request.DebugFile = new byte[0];
}
else
{
Request.DebugFile = bin;
}
Request.DebugFileName = FileName;
Request.FirmwareVersion = TextBoxFV.Text;
Request.FirmwareDescription = TextBoxFD.Text;
if (TextBoxSigningType.Text == string.Empty)
{
Request.SigningType = drp2.SelectedValue.ToString();
}
else
{
Request.SigningType = TextBoxSigningType.Text.ToUpper();
}
if (SmokeTest == null)
{
Request.SmokeTestResult = new byte[0];
}
else
{
Request.SmokeTestResult = SmokeTest;
}
SurfaceSignDBAccess.CreateSigningRequest(Request);
upon calling this function, gives error saying that "use of unassigned local variable 'Request'."
What should be the right way to call this function?
NewSigningRequest Request; - is never initialized in the method, before calling
SurfaceSignDBAccess.CreateSigningRequest(Request);
try this:
var request = new NewSigningRequest();// in the first line of code of the second code snippet.
And in the static method, remove the following code.
Request = new NewSigningRequest();

Unable to pass parameters to SSRS report in ASP.NET page

Hi I am getting an error in supplying parameters to an SSRS report deployed on server in ASP.NET page.
Please refer to the code below and let me know where is the issue?
ReportExecutionService rs = new ReportExecutionService();
string rptURL = System.Configuration.ConfigurationManager.AppSettings["rptURL"].ToString();
string rptPath = System.Configuration.ConfigurationManager.AppSettings["Page1SLScorecardReortForDownload"].ToString();
//Microsoft.Reporting.WebForms.ReportParameter[] paramlist = new Microsoft.Reporting.WebForms.ReportParameter[3];
//paramlist[0] = new Microsoft.Reporting.WebForms.ReportParameter("Week", "2013-05-03");
//paramlist[1] = new Microsoft.Reporting.WebForms.ReportParameter("year", "Fiscal Calendar 2013");
//paramlist[2] = new Microsoft.Reporting.WebForms.ReportParameter("Month", "Fiscal May, 2013");
ParameterValue[] paramlist = new ParameterValue[3];
//Microsoft.Reporting.WebForms.ReportParameter[] paramlist = new Microsoft.Reporting.WebForms.ReportParameter[3];
paramlist[0] = new ParameterValue();
paramlist[0].Name = "Week";
paramlist[0].Value = "2013-05-03";
paramlist[1] = new ParameterValue();
paramlist[1].Name = "year";
paramlist[1].Value = "Fiscal Calendar 2013";
paramlist[2] = new ParameterValue();
paramlist[2].Name = "Month";
paramlist[2].Value = "Fiscal May, 2013";
//ReportViewer1.ServerReport.SetParameters(paramlist);
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
rs.Url = rptURL;
byte[] result = null;
string reportPath = rptPath;
string format = "EXCEL";
string historyID = null;
string devInfo = #"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>";
string encoding;
string mimeType;
string extension;
ReportingWS.Warning[] warnings = null;
string[] streamIDs = null;
ReportingWS.ExecutionInfo execInfo = new ReportingWS.ExecutionInfo();
ReportingWS.ExecutionHeader execHeader = new ReportingWS.ExecutionHeader();
rs.ExecutionHeaderValue = execHeader;
execInfo = rs.LoadReport(reportPath, historyID);
rs.SetExecutionParameters(paramlist, "en-us");
String SessionId = rs.ExecutionHeaderValue.ExecutionID;
try
{
result = rs.Render(format, devInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs);
execInfo = rs.GetExecutionInfo();
}
catch (Exception ex)
{
//AlnErrorHandler.HandleError(ex);
}
parameters.Add(new ReportParameter("FyId", Convert.ToInt16(objSession.FyId).ToString()));
parameters.Add(new ReportParameter("AccountGroupId", cmbAccountGroup.SelectedValue));
parameters.Add(new ReportParameter("LedgerId", cmbLedgerId.SelectedValue));
rptvwMain.ServerReport.SetParameters(parameters);
Pass Parameters like this....

'String' does not contain a reference for 'Text'

The .Text on add is giving the error, I believe I have the right assemblies in place.
StringCollection sc = new StringCollection();
for (int i = 1; i <= 2; i++)
{
//extract the TextBox values
string txt1 = ((TextBox)Page.FindControl("TextBox1" + i.ToString())).Text;
string txt2 = ((TextBox)Page.FindControl("TextBox2" + i.ToString())).Text;
string txt3 = ((TextBox)Page.FindControl("TextBox3" + i.ToString())).Text;
string txt4 = ((TextBox)Page.FindControl("TextBox4" + i.ToString())).Text;
string txt5 = ((TextBox)Page.FindControl("TextBox5" + i.ToString())).Text;
string txt6 = ((TextBox)Page.FindControl("TextBox6" + i.ToString())).Text;
string txt7 = ((TextBox)Page.FindControl("TextBox7" + i.ToString())).Text;
string txt8 = ((TextBox)Page.FindControl("TextBox8" + i.ToString())).Text;
string txt9 = ((TextBox)Page.FindControl("TextBox9" + i.ToString())).Text;
sc.Add(txt1.Text, txt2.Text, txt3.Text, txt4.Text, txt5.Text, txt6.Text, txt7.Text, txt8.Text, txt9.Text);
}
InsertRecords(sc);
You are basically calling string.Text since the type of txt1, txt2, etc is string, hence the error. But note that you are already calling .Text on the TextField control so what you probably intend to do is:
sc.AddRange(new string[]{txt1, txt2, txt3, ...});

Resources