How to Play decrypted file - asp.net

For video's to be copy protected , I thought of
Step-1) encrypting video files with key.
step-2)Decrypting a file OR decrypt in memory stream.
Step-3) Play decrypted file OR Play from Memory stream.
I have succesfully encrypted and decrypted a video file with key. But don't know how to play decrypted file(.dnc file).
Can somebody will please help me to play video file from decrypted (File or Memory Stream).
Code for Decryption
private void Decryption(string filePath)
{
try
{
DateTime current = DateTime.Now;
string encName = filePath + "data" + ".enc";
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
#region Seperate key and data
byte[] alldata = File.ReadAllBytes(filePath);
byte[] getencryptedkey = new byte[128];
byte[] data = new byte[alldata.Length - 128];
for (int i = 0; i < alldata.Length - 128; i++)
{ data[i] = alldata[i]; }
for (int i = alldata.Length - 128, j = 0; i < alldata.Length; i++, j++)
{ getencryptedkey[j] = alldata[i]; }
using (BinaryWriter bw = new BinaryWriter(File.Create(encName)))
{
bw.Write(data);
bw.Close();
}
#endregion
#region key decryption
StreamReader reader = new StreamReader("PublicPrivateKey.xml");
string publicprivatekeyxml = reader.ReadToEnd();
RSA.FromXmlString(publicprivatekeyxml);
reader.Close();
byte[] decryptedKey = RSA.Decrypt(getencryptedkey, false);
pwd = System.Text.ASCIIEncoding.Unicode.GetString(decryptedKey);
byte[] dk = null;
byte[] div = null;
crm.getKeysFromPassword(pwd, out dk, out div);
cryptoKey = dk;
cryptoIV = div;
#endregion
string ext = Path.GetExtension(encName).ToLower();
if (ext != ".enc")
{
MessageBox.Show("Please Enter correct File");
return;
}
string dncName = Path.GetDirectoryName(encName) + "\\" + Path.GetFileNameWithoutExtension(encName);
dncName = current.Date.Day.ToString() + current.Date.Month.ToString() + current.Date.Year.ToString() + current.TimeOfDay.Duration().Hours.ToString() + current.TimeOfDay.Duration().Minutes.ToString() + current.TimeOfDay.Duration().Seconds.ToString() + ".wmv";
try
{
if (crm.DecryptData(encName, dncName, cryptoKey, cryptoIV))
{
FileInfo fi = new FileInfo(encName);
FileInfo fi2 = new FileInfo(dncName);
if ((fi.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{ fi.Attributes &= ~FileAttributes.ReadOnly; }
//copy creation and modification time
fi2.CreationTime = fi.CreationTime;
fi2.LastWriteTime = fi.LastWriteTime;
//delete encrypted file
File.Delete(encName);
MessageBox.Show("File Decrypted");
}
else
{
MessageBox.Show("The file can't be decrypted - probably wrong password");
}
}
catch (CryptographicException ex)
{ MessageBox.Show(ex.Message); }
catch (IOException ex)
{ MessageBox.Show(ex.Message); }
catch (UnauthorizedAccessException ex)
{ //i.e. readonly
MessageBox.Show(ex.Message);
}
}
catch (Exception ex)
{ MessageBox.Show(ex.Message); }
}

To copy-protect a video file, the best way to accomplish it used to be apply DRM to it. That way you can restrict how may times it should play or how long it should be available to the user, but that still could be broken via a lot of means.
You cannot make any video 100% copy protected. Please read the article below. If that was the case, the hollywood movies wouldnt be freely available via the torrent networks.
http://www.streamingmedia.com/Articles/Editorial/Featured-Articles/DRM-Is-Dead-79353.aspx

Related

FileStream Object taking forever to push file to browser

I'm using a filestream object to push a report in excel format from our DB, and it works fine for reports that are reasonable in terms the number of rows, however there's one report that has over 15K rows and the site times out after 20 minutes - I know I could increase the timeout, but even 20 minutes is unaccaptable right now. Is there any way to speed things up? Here is my current code:
string path = Server.MapPath(#"~\");
string sourceName = Path.Combine(path, "Demo", "Report_Template", templateName);
string newFileName = Path.Combine(Global.demo_data_directory, #"Reports", #"Demo Download Activity Report.xlsx"); // Path.Combine(path, "Demo_Data", "Reports", Filename + ".xlsx");
string copyresults = Utilities.CopyFile(sourceName, newFileName);
if (copyresults != "Copied file")
{
DemoDAL.ErrorLog("GenerateDownloadActivityReportFile.Page_Load: Copy Error - " + copyresults);
}
else
{
document = SpreadsheetDocument.Open(newFileName, true);
wbPart = document.WorkbookPart;
DataTable datatbl = (DataTable)Session["gvPOC"];
CreateReport(datatbl);
// ADDED THIS *********************************************************************************************************
//wbPart.Workbook.Save();
using (FileStream fsSource = new FileStream(newFileName, FileMode.Open, FileAccess.Read, FileShare.Read, 10240))
{
// Read the source file into a byte array.
byte[] bytes = new byte[fsSource.Length];
int numBytesToRead = (int)fsSource.Length;
int numBytesRead = 0;
while (numBytesToRead > 0)
{
// Read may return anything from 0 to numBytesToRead.
int n = fsSource.Read(bytes, numBytesRead, numBytesToRead);
// Break when the end of the file is reached.
if (n == 0)
break;
numBytesRead += n;
numBytesToRead -= n;
}
numBytesToRead = bytes.Length;
StreamFileToBrowser(newFileName, bytes);
}
File.Delete(newFileName);
}
public void StreamFileToBrowser(string sfilename, byte[] fileBytes)
{
try
{
Response.Clear();
Response.ClearHeaders();
Response.AppendHeader("Content-disposition", String.Format("attachment; filename=\"{0}\"", System.IO.Path.GetFileName(sfilename)));
Response.AppendHeader("Content-Type", "binary/octet-stream");
Response.AppendHeader("Content-length", fileBytes.Length.ToString());
Response.BinaryWrite(fileBytes);
if (Response.IsClientConnected)
Response.Flush();
}
catch (Exception ex)
{
DemoDAL.ErrorLog("StreamFileToBrowser: " + ex.Message);
}
}

File Encryption with the Java Cryptography Architecture using AES with a 128-bit key and PBKDF2

I am getting this error when I am decrypting a file
I am using PBKDF2 to convert a passphrase to a key and then using it. The encryption is working good but when I am trying to decrypt the same file it is giving the below error. The decrypted file gives a correct data except for the last few lines(probably the padding area). I have debugged it by outputting the IV and key while encrypting and decrypting and they both are the same but the error still exists.
public class FileEncryptorSkeleton{
private static final String progName = "FileEncryptor";
private static final int bufSize = 128;
/**
* #param args
*/
public static void main(String[] args) throws UnsupportedEncodingException {
BufferedInputStream in = null; // A buffered input stream to read from
BufferedOutputStream out = null; // And a buffered output stream to write to
SecretKeyFactory kf = null; // Something to create a key for us
KeySpec ks = null; // This is how we specify what kind of key we want it to generate
byte[] salt = new byte[20]; // Some salt for use with PBKDF2, only not very salty
SecretKey key = null; // The key that it generates
Cipher cipher = null; // The cipher that will do the real work
SecretKeySpec keyspec = null; // How we pass the key to the Cipher
int bytesRead = 0; // Number of bytes read into the input file buffer
byte[] iv = new byte[16];
// First, check the user has provided all the required arguments, and if they haven't, tell them then exit
if(args.length != 4) {
printUsageMessage(); System.exit(1);
}
// Open the input file
try {
in = new BufferedInputStream(new FileInputStream(args[1]));
} catch (FileNotFoundException e) {
printErrorMessage("Unable to open input file: " + args[1], null);
System.exit(1);
}
// And then the output file
try {
out = new BufferedOutputStream(new FileOutputStream(args[2]));
} catch (FileNotFoundException e) {
printErrorMessage("Unable to open output file: " + args[2], e);
System.exit(1);
}
try {
kf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(FileEncryptorSkeleton.class.getName()).log(Level.SEVERE, null, ex);
}
// Set up a KeySpec for password-based key generation of a 128-bit key
ks = new PBEKeySpec(args[3].toCharArray(), salt, 1000, 128);
// Now run the passphrase through PBKDF2 to get the key
try {
key = kf.generateSecret(ks);
}catch(InvalidKeySpecException e){
System.exit(1);
}
// Get the byte encoded key value as a byte array
byte[] aeskey = key.getEncoded();
// Now generate a Cipher object for AES encryption in ECBC mode with PKCS #5 padding
// Use ECB for the first task, then switch to CBC for versions 2 and 3
try {
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
} catch (NoSuchAlgorithmException e) {
printErrorMessage("No Such Algorithm Exception when creating main cipher", e);
System.exit(2);
} catch (NoSuchPaddingException e) {
printErrorMessage("No Such Padding Exception when creating main cipher",e);
System.exit(2);
}
// Set a variable to indicate whether we're in encrypt or decrypt mode, based upon args[0]
int cipherMode = -1;
char mode = Character.toLowerCase(args[0].charAt(0));
switch (mode) {
case 'e' : cipherMode = Cipher.ENCRYPT_MODE; break;
case 'd' : cipherMode = Cipher.DECRYPT_MODE; break;
default: printUsageMessage(); System.exit(1);
}
// Set up a secret key specification, based on the 16-byte (128-bit) AES key array previously generated
keyspec = new SecretKeySpec(aeskey, "AES");
IvParameterSpec ivspec = new IvParameterSpec(iv);
// Now initialize the cipher in the right mode, with the keyspec and the ivspec
try {
cipher.init(cipherMode, keyspec,ivspec);
} catch (InvalidKeyException e) {
printErrorMessage("Invalid Key Spec",e); System.exit(2);
} catch (InvalidAlgorithmParameterException ex) {
Logger.getLogger(FileEncryptorSkeleton.class.getName()).log(Level.SEVERE, null, ex);
}
// Set up some input and output byte array buffers
byte[] inputBuffer = new byte[bufSize];
byte[] outputBuffer = null;
// "Prime the pump" - we've got to read something before we can encrypt it
// and not encrypt anything if we read nothing.
try {
bytesRead = in.read(inputBuffer);
} catch (IOException e) {
printErrorMessage("Error reading input file " + args[1],e); System.exit(1);
}
// As long as we've read something, loop around encrypting, writing and reading
// bytesRead will be zero if nothing was read, or -1 on EOF - treat them both the same
while (bytesRead > 0) {
// Now encrypt this block
outputBuffer = cipher.update(inputBuffer.toString().getBytes("UTF-8"));
// Write the generated block to file
try {
out.write(outputBuffer);
} catch (IOException e) {
printErrorMessage("Error writing to output file " + args[2],e); System.exit(1);
}
// And read in the next block of the file
try {
bytesRead = in.read(inputBuffer);
} catch (IOException e) {
printErrorMessage("Error reading input file " + args[1],e); System.exit(1);
}
}
try {
// Now do the final processing
outputBuffer =cipher.doFinal(inputBuffer.toString().getBytes("UTF-8"));
cipher.init(cipherMode, keyspec,ivspec);
System.out.println(ivspec+" "+cipherMode+" "+keyspec);
} catch (IllegalBlockSizeException ex) {
Logger.getLogger(FileEncryptorSkeleton.class.getName()).log(Level.SEVERE, null, ex);
} catch (BadPaddingException ex) {
Logger.getLogger(FileEncryptorSkeleton.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidKeyException ex) {
Logger.getLogger(FileEncryptorSkeleton.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidAlgorithmParameterException ex) {
Logger.getLogger(FileEncryptorSkeleton.class.getName()).log(Level.SEVERE, null, ex);
}
// Write the final block of output
try {
out.write(outputBuffer);
} catch (IOException e) {
printErrorMessage("Error on final write to output file " + args[2],e); System.exit(1);
}
// Close the output files
try {
in.close();
out.close();
} catch (IOException e) {
printErrorMessage("Error closing file", e);
}
// If we were continuing beyond this point, we should really overwrite key material, drop KeySpecs, etc.
}
/**
* Print an error message on , optionally picking up additional detail from
* a passed exception
* #param errMsg
* #param e
*/
private static void printErrorMessage(String errMsg, Exception e) {
System.err.println(errMsg);
if (e != null)
System.err.println(e.getMessage());
}
/**
* Print a usage message
*/
private static void printUsageMessage() {
System.out.println(progName + " $Revision: 1.1 $: Usage: " + progName + " E/D infile outfile passphrase");
}
}
Oct 18, 2019 11:27:46 PM FileEncryptorSkeleton main
SEVERE: null
javax.crypto.BadPaddingException: Given final block not properly padded. Such issues can arise if a bad key is used during decryption.
at com.sun.crypto.provider.CipherCore.unpad(CipherCore.java:975)
at com.sun.crypto.provider.CipherCore.fillOutputBuffer(CipherCore.java:1056)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:853)
at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:446)
at javax.crypto.Cipher.doFinal(Cipher.java:2164)
at FileEncryptorSkeleton.main(FileEncryptorSkeleton.java:174)
Both the Cipher#update- and Cipher#doFinal-method use inputBuffer.toString(), which only contains the name of the object's class and the hashcode and not the actual data in the buffer.
It would be correct to read the first bytesRead bytes from the inputBuffer-byte[] (which were previously read from the in-BufferedInputStream) and process them (Cipher#update):
outputBuffer = cipher.update(inputBuffer, 0, bytesRead);
The loop containing the cipher#update-call is only left when no byte has been read to the inputBuffer-byte[], so that for the final processing applies (Cipher#doFinal):
outputBuffer = cipher.doFinal();
In addition, the second cipher#init-call immediately after the cipher#doFinal-call is unnecessary (Cipher#init).

asp.net upload control is not working in ipad

The asp.net upload control is uploading the file for first time in Ipad but not after that and not even showing any error
The code is as below
protected void UploadThisFile(FileUpload upload)
{
try
{
string folderpath = ConfigurationManager.AppSettings["BTCommDynamic"].ToString() + ConfigurationManager.AppSettings["Attachments"].ToString();
Guid fileguid = Guid.NewGuid();
string filename = fileguid + upload.FileName;
if (upload.HasFile && dtFiles != null)
{
DataRow drFileRow = dtFiles.NewRow();
drFileRow["FileName"] = upload.FileName;
string theFileName = Path.Combine(Server.MapPath(folderpath), filename);
string theFileName1 = Path.Combine(folderpath, filename);
//string theFileName = folderpath;
//to save the file in specified path
upload.SaveAs(theFileName);
drFileRow["FilePath"] = theFileName1;
double Filesize = (upload.FileContent.Length);
if (Filesize > 1024)
{
drFileRow["FileSize"] = (upload.FileContent.Length / 1024).ToString() + " KB";
}
else
{
drFileRow["FileSize"] = (upload.FileContent.Length).ToString() + " Bytes";
}
dtFiles.Rows.Add(drFileRow);
gvAttachment.DataSource = dtFiles;
gvAttachment.DataBind();
}
}
catch (Exception ex)
{
string message = Utility.GetExceptionMessage(ex.GetType().ToString(), ex.Message);
Display_Message(message);
}
}
Do you use firebug? There might be an error on a client side that prevents the work of your functionality.
Do you have any logic on your client side? Some kinda jquery/ajax calls?

.NET converting file to image to store in a database

Does anyone know of a way in .NET to take an incoming stream of a file and convert it to an image to be stored in the database? (Not sure if this is possible, but wanted to check).
Edit: it is not necessarily an image stream
You need to read the stream into a byte[], then save that into the database.
You can convert the image stream to byte array and store in binary or varbinary data type in database.
Here is a short example of transferring the image into a byte array in C#:
private static byte[] ReadImage(string p_postedImageFileName, string[] p_fileType)
{
bool isValidFileType = false;
try
{
FileInfo file = new FileInfo(p_postedImageFileName);
foreach (string strExtensionType in p_fileType)
{
if (strExtensionType == file.Extension)
{
isValidFileType = true;
break;
}
}
if (isValidFileType)
{
FileStream fs = new FileStream(p_postedImageFileName, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
byte[] image = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
return image;
}
return null;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion

blackberry HttpConnection.GET

URL: http://monSite/GET.asp
we must authenticate before getting the result.
I want to send the login and password with HttpConn.setRequestMethod (HttpConnection.POST) and retrieve the XML file with HttpConn.setRequestMethod (HttpConnection.GET) with the same HTTP Client.
conn = (HttpConnection) new ConnectionFactory().getConnection(_url).getConnection();
URLEncodedPostData postData = null;
postData = new URLEncodedPostData("UTF-8", false);
postData.append("userName",_username);
postData.append("passWord", _password);
conn.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LANGUAGE, "en-US");
conn.setRequestProperty(HttpProtocolConstants.HEADER_CACHE_CONTROL,"no-cache, no-store, no-transform");
// Specify the content type.
conn.setRequestMethod(HttpConnection.POST);
conn.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_TYPE, postData.getContentType());
byte [] postBytes = postData.getBytes();
conn.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LENGTH, Integer.toString(postBytes.length));
os = conn.openOutputStream();
os.write(postBytes);
os.flush();
os.close();
//GET XML file
conn.setRequestMethod(HttpConnection.GET);
conn.setRequestProperty("User-Agent",
"Profile/MIDP-1.0 Confirguration/CLDC-1.0");
if (conn.getResponseCode() == HttpConnection.HTTP_OK) {
int total = 0;
int size = 1024;
char[] buffer = new char[size];
int len;
InputStreamReader isr = new InputStreamReader(conn.openInputStream(), "UTF-8");
while ((len = isr.read(buffer, 0, size)) > 0)
{
buff.append(buffer, 0, len);
total += len;
}
result = buff.toString();
} else {
result = "Error in connection" + conn.getResponseCode();
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
conn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
the HttpConnection.POST works very well but GET no (login failed: the authentication parameter does not saved)
In HttpConnection.GET request you need to append attribute in your url like:
String url="http://www.xyz?userName="+_username+"&password="+_password+"";
and then get the InputStream
below link may be helpful for you
http://supportforums.blackberry.com/t5/Java-Development/Make-an-HTTP-Connection-to-get-a-Content-of-URL/td-p/95075

Resources