Search Results

Search found 257 results on 11 pages for 'decryption'.

Page 1/11 | 1 2 3 4 5 6 7 8 9 10 11  | Next Page >

  • XML Decryption Bug (referencing issue)

    - by OrangePekoe
    Hi, Needing some explanation of what exactly the decryption is doing, in addition to some help on solving the problem. Currently, when a portion of XML is encrypted, and then decrypted, the DOM appears to work correctly. We can see the element is encrypted and then see it return back once it is decrypted. Our problem lies when a user tries to change data in that same element after decryption has occurred. When a user changes some settings, data in the XML should change. However, if the user attempts to change an XML element that has been decrypted the changes are not reflected in the DOM. We have a reference pointer to the XML element that is used to bind the element to an object. If you encrypt the node and then decrypt it, the reference pointer now points to a valid orphaned XML element that is no longer part of the DOM. After decryption, there will be 2 copies of the XML element. One in the DOM as expected (though will not reflect new changes), and one orphaned element in memory that is still referenced by our pointer. The orphaned element is valid (reflects new changes). We can see that this orphaned element is owned by the DOM, but when we try to return its parent, it returns null. The question is: Where did this orphaned xml element come from? And how can we get it to correctly append (replace old data) to the DOM? The code resembles: public static void Decrypt(XmlDocument Doc, SymmetricAlgorithm Alg) { if (Doc == null) throw new ArgumentNullException("Doc"); if (Alg == null) throw new ArgumentNullException("Alg"); XmlElement encryptedElement = Doc.GetElementsByTagName("EncryptedData")[0] as XmlElement; if (encryptedElement == null) { throw new XmlException("The EncryptedData element was not found."); } EncryptedData edElement = new EncryptedData(); edElement.LoadXml(encryptedElement); EncryptedXml exml = new EncryptedXml(); byte[] rgbOutput = exml.DecryptData(edElement, Alg); exml.ReplaceData(encryptedElement, rgbOutput); }

    Read the article

  • .NET file Decryption - Bad Data

    - by Jon
    I am in the process of rewriting an old application. The old app stored data in a scoreboard file that was encrypted with the following code: private const String SSecretKey = @"?B?n?Mj?"; public DataTable GetScoreboardFromFile() { FileInfo f = new FileInfo(scoreBoardLocation); if (!f.Exists) { return setupNewScoreBoard(); } DESCryptoServiceProvider DES = new DESCryptoServiceProvider(); //A 64 bit key and IV is required for this provider. //Set secret key For DES algorithm. DES.Key = ASCIIEncoding.ASCII.GetBytes(SSecretKey); //Set initialization vector. DES.IV = ASCIIEncoding.ASCII.GetBytes(SSecretKey); //Create a file stream to read the encrypted file back. FileStream fsread = new FileStream(scoreBoardLocation, FileMode.Open, FileAccess.Read); //Create a DES decryptor from the DES instance. ICryptoTransform desdecrypt = DES.CreateDecryptor(); //Create crypto stream set to read and do a //DES decryption transform on incoming bytes. CryptoStream cryptostreamDecr = new CryptoStream(fsread, desdecrypt, CryptoStreamMode.Read); DataTable dTable = new DataTable("scoreboard"); dTable.ReadXml(new StreamReader(cryptostreamDecr)); cryptostreamDecr.Close(); fsread.Close(); return dTable; } This works fine. I have copied the code into my new app so that I can create a legacy loader and convert the data into the new format. The problem is I get a "Bad Data" error: System.Security.Cryptography.CryptographicException was unhandled Message="Bad Data.\r\n" Source="mscorlib" The error fires at this line: dTable.ReadXml(new StreamReader(cryptostreamDecr)); The encrypted file was created today on the same machine with the old code. I guess that maybe the encryption / decryption process uses the application name / file or something and therefore means I can not open it. Does anyone have an idea as to: A) Be able explain why this isn't working? B) Offer a solution that would allow me to be able to open files that were created with the legacy application and be able to convert them please? Here is the whole class that deals with loading and saving the scoreboard: using System; using System.Collections.Generic; using System.Text; using System.Security.Cryptography; using System.Runtime.InteropServices; using System.IO; using System.Data; using System.Xml; using System.Threading; namespace JawBreaker { [Serializable] class ScoreBoardLoader { private Jawbreaker jawbreaker; private String sSecretKey = @"?B?n?Mj?"; private String scoreBoardFileLocation = ""; private bool keepScoreBoardUpdated = true; private int intTimer = 180000; public ScoreBoardLoader(Jawbreaker jawbreaker, String scoreBoardFileLocation) { this.jawbreaker = jawbreaker; this.scoreBoardFileLocation = scoreBoardFileLocation; } // Call this function to remove the key from memory after use for security [System.Runtime.InteropServices.DllImport("KERNEL32.DLL", EntryPoint = "RtlZeroMemory")] public static extern bool ZeroMemory(IntPtr Destination, int Length); // Function to Generate a 64 bits Key. private string GenerateKey() { // Create an instance of Symetric Algorithm. Key and IV is generated automatically. DESCryptoServiceProvider desCrypto = (DESCryptoServiceProvider)DESCryptoServiceProvider.Create(); // Use the Automatically generated key for Encryption. return ASCIIEncoding.ASCII.GetString(desCrypto.Key); } public void writeScoreboardToFile() { DataTable tempScoreBoard = getScoreboardFromFile(); //add in the new scores to the end of the file. for (int i = 0; i < jawbreaker.Scoreboard.Rows.Count; i++) { DataRow row = tempScoreBoard.NewRow(); row.ItemArray = jawbreaker.Scoreboard.Rows[i].ItemArray; tempScoreBoard.Rows.Add(row); } //before it is written back to the file make sure we update the sync info if (jawbreaker.SyncScoreboard) { //connect to webservice, login and update all the scores that have not been synced. for (int i = 0; i < tempScoreBoard.Rows.Count; i++) { try { //check to see if that row has been synced to the server if (!Boolean.Parse(tempScoreBoard.Rows[i].ItemArray[7].ToString())) { //sync info to server //update the row to say that it has been updated object[] tempArray = tempScoreBoard.Rows[i].ItemArray; tempArray[7] = true; tempScoreBoard.Rows[i].ItemArray = tempArray; tempScoreBoard.AcceptChanges(); } } catch (Exception ex) { jawbreaker.writeErrorToLog("ERROR OCCURED DURING SYNC TO SERVER UPDATE: " + ex.Message); } } } FileStream fsEncrypted = new FileStream(scoreBoardFileLocation, FileMode.Create, FileAccess.Write); DESCryptoServiceProvider DES = new DESCryptoServiceProvider(); DES.Key = ASCIIEncoding.ASCII.GetBytes(sSecretKey); DES.IV = ASCIIEncoding.ASCII.GetBytes(sSecretKey); ICryptoTransform desencrypt = DES.CreateEncryptor(); CryptoStream cryptostream = new CryptoStream(fsEncrypted, desencrypt, CryptoStreamMode.Write); MemoryStream ms = new MemoryStream(); tempScoreBoard.WriteXml(ms, XmlWriteMode.WriteSchema); ms.Position = 0; byte[] bitarray = new byte[ms.Length]; ms.Read(bitarray, 0, bitarray.Length); cryptostream.Write(bitarray, 0, bitarray.Length); cryptostream.Close(); ms.Close(); //now the scores have been added to the file remove them from the datatable jawbreaker.Scoreboard.Rows.Clear(); } public void startPeriodicScoreboardWriteToFile() { while (keepScoreBoardUpdated) { //three minute sleep. Thread.Sleep(intTimer); writeScoreboardToFile(); } } public void stopPeriodicScoreboardWriteToFile() { keepScoreBoardUpdated = false; } public int IntTimer { get { return intTimer; } set { intTimer = value; } } public DataTable getScoreboardFromFile() { FileInfo f = new FileInfo(scoreBoardFileLocation); if (!f.Exists) { jawbreaker.writeInfoToLog("Scoreboard not there so creating new one"); return setupNewScoreBoard(); } else { DESCryptoServiceProvider DES = new DESCryptoServiceProvider(); //A 64 bit key and IV is required for this provider. //Set secret key For DES algorithm. DES.Key = ASCIIEncoding.ASCII.GetBytes(sSecretKey); //Set initialization vector. DES.IV = ASCIIEncoding.ASCII.GetBytes(sSecretKey); //Create a file stream to read the encrypted file back. FileStream fsread = new FileStream(scoreBoardFileLocation, FileMode.Open, FileAccess.Read); //Create a DES decryptor from the DES instance. ICryptoTransform desdecrypt = DES.CreateDecryptor(); //Create crypto stream set to read and do a //DES decryption transform on incoming bytes. CryptoStream cryptostreamDecr = new CryptoStream(fsread, desdecrypt, CryptoStreamMode.Read); DataTable dTable = new DataTable("scoreboard"); dTable.ReadXml(new StreamReader(cryptostreamDecr)); cryptostreamDecr.Close(); fsread.Close(); return dTable; } } public DataTable setupNewScoreBoard() { //scoreboard info into dataset DataTable scoreboard = new DataTable("scoreboard"); scoreboard.Columns.Add(new DataColumn("playername", System.Type.GetType("System.String"))); scoreboard.Columns.Add(new DataColumn("score", System.Type.GetType("System.Int32"))); scoreboard.Columns.Add(new DataColumn("ballnumber", System.Type.GetType("System.Int32"))); scoreboard.Columns.Add(new DataColumn("xsize", System.Type.GetType("System.Int32"))); scoreboard.Columns.Add(new DataColumn("ysize", System.Type.GetType("System.Int32"))); scoreboard.Columns.Add(new DataColumn("gametype", System.Type.GetType("System.String"))); scoreboard.Columns.Add(new DataColumn("date", System.Type.GetType("System.DateTime"))); scoreboard.Columns.Add(new DataColumn("synced", System.Type.GetType("System.Boolean"))); scoreboard.AcceptChanges(); return scoreboard; } private void Run() { // For additional security Pin the key. GCHandle gch = GCHandle.Alloc(sSecretKey, GCHandleType.Pinned); // Remove the Key from memory. ZeroMemory(gch.AddrOfPinnedObject(), sSecretKey.Length * 2); gch.Free(); } } }

    Read the article

  • C# file Decryption - Bad Data

    - by Jon
    Hi all, I am in the process of rewriting an old application. The old app stored data in a scoreboard file that was encrypted with the following code: private const String SSecretKey = @"?B?n?Mj?"; public DataTable GetScoreboardFromFile() { FileInfo f = new FileInfo(scoreBoardLocation); if (!f.Exists) { return setupNewScoreBoard(); } DESCryptoServiceProvider DES = new DESCryptoServiceProvider(); //A 64 bit key and IV is required for this provider. //Set secret key For DES algorithm. DES.Key = ASCIIEncoding.ASCII.GetBytes(SSecretKey); //Set initialization vector. DES.IV = ASCIIEncoding.ASCII.GetBytes(SSecretKey); //Create a file stream to read the encrypted file back. FileStream fsread = new FileStream(scoreBoardLocation, FileMode.Open, FileAccess.Read); //Create a DES decryptor from the DES instance. ICryptoTransform desdecrypt = DES.CreateDecryptor(); //Create crypto stream set to read and do a //DES decryption transform on incoming bytes. CryptoStream cryptostreamDecr = new CryptoStream(fsread, desdecrypt, CryptoStreamMode.Read); DataTable dTable = new DataTable("scoreboard"); dTable.ReadXml(new StreamReader(cryptostreamDecr)); cryptostreamDecr.Close(); fsread.Close(); return dTable; } This works fine. I have copied the code into my new app so that I can create a legacy loader and convert the data into the new format. The problem is I get a "Bad Data" error: System.Security.Cryptography.CryptographicException was unhandled Message="Bad Data.\r\n" Source="mscorlib" The error fires at this line: dTable.ReadXml(new StreamReader(cryptostreamDecr)); The encrypted file was created today on the same machine with the old code. I guess that maybe the encryption / decryption process uses the application name / file or something and therefore means I can not open it. Does anyone have an idea as to: A) Be able explain why this isn't working? B) Offer a solution that would allow me to be able to open files that were created with the legacy application and be able to convert them please? Thank you

    Read the article

  • Encryption-Decryption in Rails

    - by Salil
    Hi All, I am using require 'digest/sha1' to encrypt my password and save into database. During login I authenticate by matching the encrypted password saved in database and again encrypted the one use enter in password field. As of now everything works fine but now I want to do 'Forgot Password' functionality. To do this I need to decrypt the password which is saved in database to find original one. How to decrypt using digest/sha1? Or does anyone know any algorithm which supports encryption & decryption as well? I am using ruby on rails so I need Ruby way to accomplish it.

    Read the article

  • NSData-AES Class Encryption/Decryption in Cocoa

    - by David Schiefer
    hi, I am attempting to encrypt/decrypt a plain text file in my text editor. encrypting seems to work fine, but the decrypting does not work, the text comes up encrypted. I am certain i've decrypted the text using the word i encrypted it with - could someone look through the snippet below and help me out? Thanks :) Encrypting: NSAlert *alert = [NSAlert alertWithMessageText:@"Encryption" defaultButton:@"Set" alternateButton:@"Cancel" otherButton:nil informativeTextWithFormat:@"Please enter a password to encrypt your file with:"]; [alert setIcon:[NSImage imageNamed:@"License.png"]]; NSSecureTextField *input = [[NSSecureTextField alloc] initWithFrame:NSMakeRect(0, 0, 300, 24)]; [alert setAccessoryView:input]; NSInteger button = [alert runModal]; if (button == NSAlertDefaultReturn) { [[NSUserDefaults standardUserDefaults] setObject:[input stringValue] forKey:@"password"]; NSData *data; [self setString:[textView textStorage]]; NSMutableDictionary *dict = [NSDictionary dictionaryWithObject:NSPlainTextDocumentType forKey:NSDocumentTypeDocumentAttribute]; [textView breakUndoCoalescing]; data = [[self string] dataFromRange:NSMakeRange(0, [[self string] length]) documentAttributes:dict error:outError]; NSData*encrypt = [data AESEncryptWithPassphrase:[input stringValue]]; [encrypt writeToFile:[absoluteURL path] atomically:YES]; Decrypting: NSAlert *alert = [NSAlert alertWithMessageText:@"Decryption" defaultButton:@"Open" alternateButton:@"Cancel" otherButton:nil informativeTextWithFormat:@"This file has been protected with a password.To view its contents,enter the password below:"]; [alert setIcon:[NSImage imageNamed:@"License.png"]]; NSSecureTextField *input = [[NSSecureTextField alloc] initWithFrame:NSMakeRect(0, 0, 300, 24)]; [alert setAccessoryView:input]; NSInteger button = [alert runModal]; if (button == NSAlertDefaultReturn) { NSLog(@"Entered Password - attempting to decrypt."); NSMutableDictionary *dict = [NSDictionary dictionaryWithObject:NSPlainTextDocumentType forKey:NSDocumentTypeDocumentOption]; NSData*decrypted = [[NSData dataWithContentsOfFile:[self fileName]] AESDecryptWithPassphrase:[input stringValue]]; mString = [[NSAttributedString alloc] initWithData:decrypted options:dict documentAttributes:NULL error:outError];

    Read the article

  • Python byte per byte XOR decryption

    - by neurino
    I have an XOR encypted file by a VB.net program using this function to scramble: Public Class Crypter ... 'This Will convert String to bytes, then call the other function. Public Function Crypt(ByVal Data As String) As String Return Encoding.Default.GetString(Crypt(Encoding.Default.GetBytes(Data))) End Function 'This calls XorCrypt giving Key converted to bytes Public Function Crypt(ByVal Data() As Byte) As Byte() Return XorCrypt(Data, Encoding.Default.GetBytes(Me.Key)) End Function 'Xor Encryption. Private Function XorCrypt(ByVal Data() As Byte, ByVal Key() As Byte) As Byte() Dim i As Integer If Key.Length <> 0 Then For i = 0 To Data.Length - 1 Data(i) = Data(i) Xor Key(i Mod Key.Length) Next End If Return Data End Function End Class and saved this way: Dim Crypter As New Cryptic(Key) 'open destination file Dim objWriter As New StreamWriter(fileName) 'write crypted content objWriter.Write(Crypter.Crypt(data)) Now I have to reopen the file with Python but I have troubles getting single bytes, this is the XOR function in python: def crypto(self, data): 'crypto(self, data) -> str' return ''.join(chr((ord(x) ^ ord(y)) % 256) \ for (x, y) in izip(data.decode('utf-8'), cycle(self.key)) I had to add the % 256 since sometimes x is 256 i.e. not a single byte. This thing of two bytes being passed does not break the decryption because the key keeps "paired" with the following data. The problem is some decrypted character in the conversion is wrong. These chars are all accented letters like à, è, ì but just a few of the overall accented letters. The others are all correctly restored. I guess it could be due to the 256 mod but without it I of course get a chr exception... Thanks for your support

    Read the article

  • Is encoding needed in this decryption?

    - by Lijo
    I have a Encryption – Decryption scenario as shown below. //[Clear text ID string as input] -- [(ASCII GetByte) + Encoding] -- [Encrption as byte array] -- [Database column is in VarBinary] -- [Pass byte[] as VarBinary parameter to SP for comparison] //[ID stored as VarBinary in Database] -- [Read as byte array] -- [(Decrypt as byte array) + Encoding + (ASCII Get String)] -- Show as string in the UI My question is in the decryption scenario. After decryption I get a byte array. I am doing an encoding (IBM037) after that. Is it correct? Is there something wrong in the flow shown above? private static byte[] GetEncryptedID(string id) { Interface_Request input = new Interface_Request(); input.RequestText = Encodeto64(id); input.RequestType = Encryption; ProgramInterface inputRequest = new ProgramInterface(); inputRequest.Test_Trial_Request = input; using (KTestService operation = new KTestService()) { return ((operation.KTrialOperation(inputRequest)).Test_Trial_Response.ResponseText); } } private static string GetDecryptedID(byte[] id) { Interface_Request input = new Interface_Request(); input.RequestText = id; input.RequestType = Decryption; ProgramInterface request = new ProgramInterface(); request.Test_Trial_Request = input; using (KTestService operationD = new KTestService()) { ProgramInterface1 response = operationD.KI014Operation(request); byte[] decryptedValue = response.ICSF_AES_Response.ResponseText; Encoding sourceByteFormat = Encoding.GetEncoding("IBM037"); Encoding destinationByteFormat = Encoding.ASCII; //Convert from one byte format to other (IBM to ASCII) byte[] ibmEncodedBytes = Encoding.Convert(sourceByteFormat, destinationByteFormat,decryptedValue); return System.Text.ASCIIEncoding.ASCII.GetString(ibmEncodedBytes); } } private static byte[] EncodeTo64(string toEncode) { byte[] dataInBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode); Encoding destinationByteFormat = Encoding.GetEncoding("IBM037"); Encoding sourceByteFormat = Encoding.ASCII; //Convert from one byte format to other (ASCII to IBM) byte[] asciiBytes = Encoding.Convert(sourceByteFormat, destinationByteFormat, dataInBytes); return asciiBytes; }

    Read the article

  • Exception - Illegal Block size during decryption(Android)

    - by Vamsi
    I am writing an application which encrypts and decrypts the user notes based on the user set password. i used the following algorithms for encryption/decryption 1. PBEWithSHA256And256BitAES-CBC-BC 2. PBEWithMD5And128BitAES-CBC-OpenSSL e_Cipher = Cipher.getInstance(PBEWithSHA256And256BitAES-CBC-BC); d_Cipher = Cipher.getInstance(PBEWithSHA256And256BitAES-CBC-BC); e_Cipher.init() d_Cipher.init() encryption is working well, but when trying to decrypt it gives Exception - Illegal Block size after encryption i am converting the cipherText to HEX and storing it in a sqlite database. i am retrieving correct values from the sqlite database during decyption but when calling d_Cipher.dofinal() it throws the Exception. I thought i missed to specify the padding and tried to check what are the other available cipher algorithms but i was unable to found. so request you to please give the some knowledge on what are the cipher algorithms and padding that are supported by Android? if the algorithm which i used can be used for padding, how should i specify the padding mechanism? I am pretty new to Encryption so tried a couple of algorithms which are available in BouncyCastle.java but unsuccessful. As requested here is the code public class CryptoHelper { private static final String TAG = "CryptoHelper"; //private static final String PBEWithSHA256And256BitAES = "PBEWithSHA256And256BitAES-CBC-BC"; //private static final String PBEWithSHA256And256BitAES = "PBEWithMD5And128BitAES-CBC-OpenSSL"; private static final String PBEWithSHA256And256BitAES = "PBEWithMD5And128BitAES-CBC-OpenSSLPBEWITHSHA1AND3-KEYTRIPLEDES-CB"; private static final String randomAlgorithm = "SHA1PRNG"; public static final int SALT_LENGTH = 8; public static final int SALT_GEN_ITER_COUNT = 20; private final static String HEX = "0123456789ABCDEF"; private Cipher e_Cipher; private Cipher d_Cipher; private SecretKey secretKey; private byte salt[]; public CryptoHelper(String password) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeySpecException { char[] cPassword = password.toCharArray(); PBEKeySpec pbeKeySpec = new PBEKeySpec(cPassword); PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, SALT_GEN_ITER_COUNT); SecretKeyFactory keyFac = SecretKeyFactory.getInstance(PBEWithSHA256And256BitAES); secretKey = keyFac.generateSecret(pbeKeySpec); SecureRandom saltGen = SecureRandom.getInstance(randomAlgorithm); this.salt = new byte[SALT_LENGTH]; saltGen.nextBytes(this.salt); e_Cipher = Cipher.getInstance(PBEWithSHA256And256BitAES); d_Cipher = Cipher.getInstance(PBEWithSHA256And256BitAES); e_Cipher.init(Cipher.ENCRYPT_MODE, secretKey, pbeParamSpec); d_Cipher.init(Cipher.DECRYPT_MODE, secretKey, pbeParamSpec); } public String encrypt(String cleartext) throws IllegalBlockSizeException, BadPaddingException { byte[] encrypted = e_Cipher.doFinal(cleartext.getBytes()); return convertByteArrayToHex(encrypted); } public String decrypt(String cipherString) throws IllegalBlockSizeException { byte[] plainText = decrypt(convertStringtobyte(cipherString)); return(new String(plainText)); } public byte[] decrypt(byte[] ciphertext) throws IllegalBlockSizeException { byte[] retVal = {(byte)0x00}; try { retVal = d_Cipher.doFinal(ciphertext); } catch (BadPaddingException e) { Log.e(TAG, e.toString()); } return retVal; } public String convertByteArrayToHex(byte[] buf) { if (buf == null) return ""; StringBuffer result = new StringBuffer(2*buf.length); for (int i = 0; i < buf.length; i++) { appendHex(result, buf[i]); } return result.toString(); } private static void appendHex(StringBuffer sb, byte b) { sb.append(HEX.charAt((b>>4)&0x0f)).append(HEX.charAt(b&0x0f)); } private static byte[] convertStringtobyte(String hexString) { int len = hexString.length()/2; byte[] result = new byte[len]; for (int i = 0; i < len; i++) { result[i] = Integer.valueOf(hexString.substring(2*i, 2*i+2), 16).byteValue(); } return result; } public byte[] getSalt() { return salt; } public SecretKey getSecretKey() { return secretKey; } public static SecretKey createSecretKey(char[] password) throws NoSuchAlgorithmException, InvalidKeySpecException { PBEKeySpec pbeKeySpec = new PBEKeySpec(password); SecretKeyFactory keyFac = SecretKeyFactory.getInstance(PBEWithSHA256And256BitAES); return keyFac.generateSecret(pbeKeySpec); } } I will call mCryptoHelper.decrypt(String str) then this results in Illegal block size exception My Env: Android 1.6 on Eclipse

    Read the article

  • Padding error when using RSA Encryption in C# and Decryption in Java

    - by Matt Shaver
    Currently I am receiving the following error when using Java to decrypt a Base64 encoded RSA encrypted string that was made in C#: javax.crypto.BadPaddingException: Not PKCS#1 block type 2 or Zero padding The setup process between the exchange from .NET and Java is done by creating a private key in the .NET key store then from the PEM file extracted, created use keytool to create a JKS version with the private key. Java loads the already created JKS and decodes the Base64 string into a byte array and then uses the private key to decrypt. Here is the code that I have in C# that creates the encrypted string: public string Encrypt(string value) { byte[] baIn = null; byte[] baRet = null; string keyContainerName = "test"; CspParameters cp = new CspParameters(); cp.Flags = CspProviderFlags.UseMachineKeyStore; cp.KeyContainerName = keyContainerName; RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cp); // Convert the input string to a byte array baIn = UnicodeEncoding.Unicode.GetBytes(value); // Encrypt baRet = rsa.Encrypt(baIn, false); // Convert the encrypted byte array to a base64 string return Convert.ToBase64String(baRet); } Here is the code that I have in Java that decrypts the inputted string: public void decrypt(String base64String) { String keyStorePath = "C:\Key.keystore"; String storepass = "1234"; String keypass = "abcd"; byte[] data = Base64.decode(base64String); byte[] cipherData = null; keystore = KeyStore.getInstance("JKS"); keystore.load(new FileInputStream(keyStorePath), storepass.toCharArray()); RSAPrivateKey privateRSAKey = (RSAPrivateKey) keystore.getKey(alias, keypass.toCharArray()); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.DECRYPT_MODE, privateRSAKey); cipherData = cipher.doFinal(data); System.out.println(new String(cipherData)); } Does anyone see a step missing or where the padding or item needs to be changed? I have done hours of reading on this site and others but haven't really found a concrete solution. You're help is vastly appreciated. Thanks. -Matt

    Read the article

  • encryption decryption function in php

    - by parthav
    import gnupg, urllib retk = urllib.urlopen("http://keyserver.pramberger.at/pks/" "lookup?op=get&search=userid for the key is required") pub_key = retk.read() #print pub_key gpg = gnupg.GPG(gnupghome="/tmp/foldername", verbose=True) print "Import the Key :", gpg.import_keys(pub_key).summary() print "Encrypt the Message:" msg = "Hellllllllllo" uid = "userid that has the key on public key server" enc = gpg.encrypt(msg, uid,always_trust=True) print "*The enc content***************************== ", enc this function written in python gives me encrypted message.The encryption is done using the public key which i am getting from public key server(pramberger.at). Now how can i implement the same functionality (getting the key from any public key server and using that key encrypt the message) in php

    Read the article

  • How do I install a DVD decryption library?

    - by rocket101
    I recently built a computer running Ubuntu 11.10. It works great, except for one thing. With some video DVDs, when I insert them into my drive, the movie player just says "An error occurred. Could not read DVD. This may be because the DVD is encrypted and a DVD decryption library is not installed." My mac plays the DVD just fine. What is a DVD decryption library, and how can I install it? Thanks! EDIT: I need LEGAL way to do this. All I want is to be able to use this computer as a HTPC!

    Read the article

  • Padding error - when using AES Encryption in Java and Decryption in C

    - by user234445
    Hi All, I have a problem while decrypting the xl file in rijndael 'c' code (The file got encrypted in Java through JCE) and this problem is happening only for the excel files types which having formula's. Remaining all file type encryption/decryption is happening properly. (If i decrypt the same file in java the output is coming fine.) While i am dumped a file i can see the difference between java decryption and 'C' file decryption. od -c -b filename(file decrypted in C) 0034620 005 006 \0 \0 \0 \0 022 \0 022 \0 320 004 \0 \0 276 4 005 006 000 000 000 000 022 000 022 000 320 004 000 000 276 064 0034640 \0 \0 \0 \0 \f \f \f \f \f \f \f \f \f \f \f \f 000 000 000 000 014 014 014 014 014 014 014 014 014 014 014 014 0034660 od -c -b filename(file decrypted in Java) 0034620 005 006 \0 \0 \0 \0 022 \0 022 \0 320 004 \0 \0 276 4 005 006 000 000 000 000 022 000 022 000 320 004 000 000 276 064 0034640 \0 \0 \0 \0 000 000 000 000 0034644 (the above is the difference between the dumped files) The following java code i used to encrypt the file. public class AES { /** * Turns array of bytes into string * * @param buf Array of bytes to convert to hex string * @return Generated hex string */ public static void main(String[] args) throws Exception { File file = new File("testxls.xls"); byte[] lContents = new byte[(int) file.length()]; try { FileInputStream fileInputStream = new FileInputStream(file); fileInputStream.read(lContents); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } try { KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(256); // 192 and 256 bits may not be available // Generate the secret key specs. SecretKey skey = kgen.generateKey(); //byte[] raw = skey.getEncoded(); byte[] raw = "aabbccddeeffgghhaabbccddeeffgghh".getBytes(); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec); byte[] encrypted = cipher.doFinal(lContents); cipher.init(Cipher.DECRYPT_MODE, skeySpec); byte[] original = cipher.doFinal(lContents); FileOutputStream f1 = new FileOutputStream("testxls_java.xls"); f1.write(original); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } I used the following file for decryption in 'C'. #include <stdio.h> #include "rijndael.h" #define KEYBITS 256 #include <stdio.h> #include "rijndael.h" #define KEYBITS 256 int main(int argc, char **argv) { unsigned long rk[RKLENGTH(KEYBITS)]; unsigned char key[KEYLENGTH(KEYBITS)]; int i; int nrounds; char dummy[100] = "aabbccddeeffgghhaabbccddeeffgghh"; char *password; FILE *input,*output; password = dummy; for (i = 0; i < sizeof(key); i++) key[i] = *password != 0 ? *password++ : 0; input = fopen("doc_for_logu.xlsb", "rb"); if (input == NULL) { fputs("File read error", stderr); return 1; } output = fopen("ori_c_res.xlsb","w"); nrounds = rijndaelSetupDecrypt(rk, key, 256); while (1) { unsigned char plaintext[16]; unsigned char ciphertext[16]; int j; if (fread(ciphertext, sizeof(ciphertext), 1, input) != 1) break; rijndaelDecrypt(rk, nrounds, ciphertext, plaintext); fwrite(plaintext, sizeof(plaintext), 1, output); } fclose(input); fclose(output); }

    Read the article

  • ecryptfs - decrypt and mount at boot with USB key

    - by Josh McGee
    I have a system running Ubuntu Server as a testbed for some services that I want to get familiar with. I decided to let the installation procedure set up encryption. I knew all along that I would have to decrypt it with the passphrase in order to get the system booted, but I assumed it wouldn't matter since it will only boot once or twice a month. However, my brother has informed me that he is a victim of power outages at the residence where this server is located. This means we have to explain to his girlfriend how to turn on the computer, attach a keyboard, connect a monitor (she just can't understand that she can type to the computer without a display, so whatever) and input the passphrase for us, while we are at work. I have arrived at the conclusion that I should just put together a USB key that can be plugged in before powering on the computer, to avoid all the trouble. Is this possible with ecryptfs? Is there a tutorial or simple list of instructions available so that I can knock this out and focus back on the stuff I care about? EDIT: I am aware that this is possible with LUKS and dm-crypt, but unfortunately the magical encryption that Ubuntu hands you during the installation is only ecryptfs so my question is specific to that.

    Read the article

  • unable to decrypt certain files with secret key pgp 6.5.8, any advice?

    - by pythonian29033
    Ok so I do some stuff for a client of ours that requires me to decrypt some of their suppliers messages, the thing is, something weird happened the other day and I can only decrypt some files with an old decryption script, but for certain files I get the error: "Message is encrypted. Cannot decrypt message. It can only be decrypted by: 2048 bits, Key ID 98627E12, Created 2000-03-02 "Other Guy "" as you can see, the key is ancient and I was still 9years old when it was created, so I have know idea who this "Other Guy" is. . .and I can't understand why I'm able to decrypt some of the supplier's files with the decryption script, but for others it fails. PS: the supplier only uses one public key, so this should work for all the files, any advice?

    Read the article

  • oData/ADO.NET Data Services using LINQ-to-SQL with a decryption layer

    - by Program.X
    I have written an application using LINQ-to-SQL that submits a web form into a database. I absact the LINQ-to-SQL away using a Repository pattern. This repository has the basic methods: Get(), Save(), etc. As a development of the project, I needed to encrypt certain fields in the form. This was trivial, as I just added the encryption calls to the Get(), Save() methods in the Repository. Now, I want to put an oData layer over it, to allow RESTful extraction from MS Excel 2010 (when it comes out). I have this working, after a few stumbles on useless error messages, etc. However, obviously, those encrypted fields are still encrypted. My repository pattern would have decrypted these for me. As far as I know, I have to directly bind my oData service to the LINQ-to-SQL context for the schema, etc. to work - unless I enter a whole world of pain (any URLs appreciated). Is there a way I can insert my encryption/decryption layer into the request so decryption is done "on the fly"? I looked at the OnStartProcessingRequest() overload of DataService but this doesn't seem that useful.

    Read the article

  • AES decryption in Java - IvParameterSpec to big

    - by user1277269
    Im going to decrypt a plaintext with two keys. As you see in the picture were have one encrypted file wich contains KEY1(128 bytes),KEYIV(128 bytes),key2(128bytes) wich is not used in this case then we have the ciphertext. The error I get here is "Exception in thread "main" java.security.InvalidAlgorithmParameterException: Wrong IV length: must be 16 bytes long. but it is 64 bytes." Picture: http://i264.photobucket.com/albums/ii200/XeniuM05/bg_zps0a523659.png public class AES { public static void main(String[] args) throws Exception { byte[] encKey1 = new byte[128]; byte[] EncIV = new byte[256]; byte[] UnEncIV = new byte[128]; byte[] unCrypKey = new byte[128]; byte[] unCrypText = new byte[1424]; File f = new File("C://ftp//ciphertext.enc"); FileInputStream fis = new FileInputStream(F); byte[] EncText = new byte[(int) f.length()]; fis.read(encKey1); fis.read(EncIV); fis.read(EncText); EncIV = Arrays.copyOfRange(EncIV, 128, 256); EncText = Arrays.copyOfRange(EncText, 384, EncText.length); System.out.println(EncText.length); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); char[] password = "lab1StorePass".toCharArray(); java.io.FileInputStream fos = new java.io.FileInputStream( "C://ftp//lab1Store"); ks.load(fos, password); char[] passwordkey1 = "lab1KeyPass".toCharArray(); PrivateKey Lab1EncKey = (PrivateKey) ks.getKey("lab1EncKeys", passwordkey1); Cipher rsaDec = Cipher.getInstance("RSA"); // set cipher to RSA decryption rsaDec.init(Cipher.DECRYPT_MODE, Lab1EncKey); // initalize cipher ti lab1key unCrypKey = rsaDec.doFinal(encKey1); // Decryps first key UnEncIV = rsaDec.doFinal(EncIV); //decryps encive byte array to undecrypted bytearray---- OBS! Error this is 64 BYTES big, we want 16? System.out.println("lab1key "+ unCrypKey +" IV " + UnEncIV); //-------CIPHERTEXT decryption--------- Cipher AESDec = Cipher.getInstance("AES/CBC/PKCS5Padding"); //---------convert decrypted bytearrays to acctual keys SecretKeySpec unCrypKey1 = new SecretKeySpec(unCrypKey, "AES"); IvParameterSpec ivSpec = new IvParameterSpec(UnEncIV); AESDec.init(Cipher.DECRYPT_MODE, unCrypKey1, ivSpec ); unCrypText = AESDec.doFinal(EncText); // Convert decrypted cipher bytearray to string String deCryptedString = new String(unCrypKey); System.out.println(deCryptedString); }

    Read the article

  • standard encryption decryption across different platforms

    - by Raj
    hey guys i need to implement a standard encryption decryption logic across an entire project platform which has different clients implemented using different platforms as follows: 1) iphone app (objectiv c) 2) website (classic asp) 3) webservice (asp.net) the iphone app as well as the website need to send info to webservice using encrypted query strings the web service then decrypts this and processes the info further wanted to know the simplest way to achieve this. is there some free and ready to use binary available with an easy to use api to achieve this? encryption needs to be as secure as possible thnx in advance

    Read the article

  • CryptoExcercise Encryption/Decryption Problem

    - by venkat
    I am using apples "cryptoexcercise" (Security.Framework) in my application to encrypt and decrypt a data of numeric value. When I give the input 950,128 the values got encrypted, but it is not getting decrypted and exists with the encrypted value only. This happens only with the mentioned numeric values. Could you please check this issue and give the solution to solve this problem? here is my code (void)testAsymmetricEncryptionAndDecryption { uint8_t *plainBuffer; uint8_t *cipherBuffer; uint8_t *decryptedBuffer; const char inputString[] = "950"; int len = strlen(inputString); if (len > BUFFER_SIZE) len = BUFFER_SIZE-1; plainBuffer = (uint8_t *)calloc(BUFFER_SIZE, sizeof(uint8_t)); cipherBuffer = (uint8_t *)calloc(CIPHER_BUFFER_SIZE, sizeof(uint8_t)); decryptedBuffer = (uint8_t *)calloc(BUFFER_SIZE, sizeof(uint8_t)); strncpy( (char *)plainBuffer, inputString, len); NSLog(@"plain text : %s", plainBuffer); [self encryptWithPublicKey:(UInt8 *)plainBuffer cipherBuffer:cipherBuffer]; NSLog(@"encrypted data: %s", cipherBuffer); [self decryptWithPrivateKey:cipherBuffer plainBuffer:decryptedBuffer]; NSLog(@"decrypted data: %s", decryptedBuffer); free(plainBuffer); free(cipherBuffer); free(decryptedBuffer); } (void)encryptWithPublicKey:(uint8_t *)plainBuffer cipherBuffer:(uint8_t *)cipherBuffer { OSStatus status = noErr; size_t plainBufferSize = strlen((char *)plainBuffer); size_t cipherBufferSize = CIPHER_BUFFER_SIZE; NSLog(@"SecKeyGetBlockSize() public = %d", SecKeyGetBlockSize([self getPublicKeyRef])); // Error handling // Encrypt using the public. status = SecKeyEncrypt([self getPublicKeyRef], PADDING, plainBuffer, plainBufferSize, &cipherBuffer[0], &cipherBufferSize ); NSLog(@"encryption result code: %d (size: %d)", status, cipherBufferSize); NSLog(@"encrypted text: %s", cipherBuffer); } (void)decryptWithPrivateKey:(uint8_t *)cipherBuffer plainBuffer:(uint8_t *)plainBuffer { OSStatus status = noErr; size_t cipherBufferSize = strlen((char *)cipherBuffer); NSLog(@"decryptWithPrivateKey: length of buffer: %d", BUFFER_SIZE); NSLog(@"decryptWithPrivateKey: length of input: %d", cipherBufferSize); // DECRYPTION size_t plainBufferSize = BUFFER_SIZE; // Error handling status = SecKeyDecrypt([self getPrivateKeyRef], PADDING, &cipherBuffer[0], cipherBufferSize, &plainBuffer[0], &plainBufferSize ); NSLog(@"decryption result code: %d (size: %d)", status, plainBufferSize); NSLog(@"FINAL decrypted text: %s", plainBuffer); } (SecKeyRef)getPublicKeyRef { OSStatus sanityCheck = noErr; SecKeyRef publicKeyReference = NULL; if (publicKeyRef == NULL) { NSMutableDictionary *queryPublicKey = [[NSMutableDictionary alloc] init]; // Set the public key query dictionary. [queryPublicKey setObject:(id)kSecClassKey forKey:(id)kSecClass]; [queryPublicKey setObject:publicTag forKey:(id)kSecAttrApplicationTag]; [queryPublicKey setObject:(id)kSecAttrKeyTypeRSA forKey:(id)kSecAttrKeyType]; [queryPublicKey setObject:[NSNumber numberWithBool:YES] forKey:(id)kSecReturnRef]; // Get the key. sanityCheck = SecItemCopyMatching((CFDictionaryRef)queryPublicKey, (CFTypeRef *)&publicKeyReference); if (sanityCheck != noErr) { publicKeyReference = NULL; } [queryPublicKey release]; } else { publicKeyReference = publicKeyRef; } return publicKeyReference; } (SecKeyRef)getPrivateKeyRef { OSStatus resultCode = noErr; SecKeyRef privateKeyReference = NULL; if(privateKeyRef == NULL) { NSMutableDictionary * queryPrivateKey = [[NSMutableDictionary alloc] init]; // Set the private key query dictionary. [queryPrivateKey setObject:(id)kSecClassKey forKey:(id)kSecClass]; [queryPrivateKey setObject:privateTag forKey:(id)kSecAttrApplicationTag]; [queryPrivateKey setObject:(id)kSecAttrKeyTypeRSA forKey:(id)kSecAttrKeyType]; [queryPrivateKey setObject:[NSNumber numberWithBool:YES] forKey:(id)kSecReturnRef]; // Get the key. resultCode = SecItemCopyMatching((CFDictionaryRef)queryPrivateKey, (CFTypeRef *)&privateKeyReference); NSLog(@"getPrivateKey: result code: %d", resultCode); if(resultCode != noErr) { privateKeyReference = NULL; } [queryPrivateKey release]; } else { privateKeyReference = privateKeyRef; } return privateKeyReference; }

    Read the article

  • RSA encryption/ Decryption in a client server application

    - by user308806
    Hi guys, probably missing something very straight forward on this, but please forgive me, I'm very naive! Have a client server application where the client identifies its self with an RSA encrypted username & password. Unfortunately I'm getting a "bad padding exception: data must start with zero" when i try to decrypt with the public key on the client side. I'm fairly sure the key is correct as I have tested encrypting with public key then decrypting with private key on the client side with no problems at all. Just seems when I transfer it over the connection it messses it up somehow?! Using PrintWriter & BufferedReader on the sockets if thats of importance. EncodeBASE64 & DecodeBASE64 encode byte[] to 64base and vice versa respectively. Any ideas guys?? Client side: Socket connectionToServer = new Socket("127.0.0.1", 7050); InputStream in = connectionToServer.getInputStream(); DataInputStream dis = new DataInputStream(in); int length = dis.readInt(); byte[] data = new byte[length]; // dis.readFully(data); dis.read(data); System.out.println("The received Data*****************************************"); System.out.println("The length of bits "+ length); System.out.println(data); System.out.println("***********************************************************"); Decryption d = new Decryption(); byte [] ttt = d.decrypt(data); System.out.print(data); String ss = new String(ttt); System.out.println("***********************"); System.out.println(ss); System.out.println("************************"); Server Side: in = connectionFromClient.getInputStream(); OutputStream out = connectionFromClient.getOutputStream(); DataOutputStream dataOut = new DataOutputStream(out); LicenseList licenses = new LicenseList(); String ValidIDs = licenses.getAllIDs(); System.out.println(ValidIDs); Encryption enc = new Encryption(); byte[] encrypted = enc.encrypt(ValidIDs); byte[] dd = enc.encrypt(ValidIDs); String tobesent = new String(dd); //byte[] rsult = enc.decrypt(dd); //String tt = String(rsult); System.out.println("The sent data**********************************************"); System.out.println(dd); String temp = new String(dd); System.out.println(temp); System.out.println("*************************************************************"); //BufferedWriter bf = new BufferedWriter(OutputStreamWriter(out)); //dataOut.write(ValidIDs.getBytes().length); dataOut.writeInt(ValidIDs.getBytes().length); dataOut.flush(); dataOut.write(encrypted); dataOut.flush(); System.out.println("********Testing**************"); System.out.println("Here are the ids:::"); System.out.println(licenses.getAllIDs()); System.out.println("**********************"); //bw.write("it is working well\n");

    Read the article

  • AES encryption/decryption java bouncy castle explanation?

    - by Programmer0
    Can someone please explain what this program is doing pointing out some of the major points? I'm looking at the code and I'm completely lost. I just need explanation on the encryption/decryption phases. I think it generates an AES 192 key at one point but I'm not 100% sure. I'm not sure what the byte/ivBytes are used for either. import java.security.Key; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.spec.IvParameterSpec; public class RandomKey { public static void main(String[] args) throws Exception { byte[] input = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 }; byte[] ivBytes = new byte[] { 0x00, 0x00, 0x00, 0x01, 0x04, 0x05, 0x06, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 }; //initializing a new initialization vector IvParameterSpec ivSpec = new IvParameterSpec(ivBytes); //what does this actually do? Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding", "BC"); //what does this do? KeyGenerator generator = KeyGenerator.getInstance("AES","BC"); //I assume this generates a key size of 192 bits generator.init(192); //does this generate a random key? Key encryptKey = generator.generateKey(); System.out.println("input: " +toHex(input)); //encryption phase cipher.init(Cipher.ENCRYPT_MODE, encryptKey, ivSpec); //what is this doing? byte[] cipherText = new byte[cipher.getOutputSize(input.length)]; //what is this doing? int ctLength = cipher.update(input, 0, input.length, cipherText,0); //getting the cipher text length i assume? ctLength += cipher.doFinal (cipherText, ctLength ); System.out.println ("Cipher: " +toHex(cipherText) + " bytes: " + ctLength); //decryption phase cipher.init(Cipher.DECRYPT_MODE, encryptKey, ivSpec); //storing the ciphertext in plaintext i'm assuming? byte[] plainText = new byte[cipher.getOutputSize(ctLength)]; int ptLength = cipher.update(cipherText, 0, ctLength, plainText, 0); //getting plaintextLength i think? ptLength= cipher.doFinal (plainText, ptLength); System.out.println("plain: " + toHex(plainText, ptLength)); } private static String digits = "0123456789abcdef"; public static String toHex(byte[] data, int length) { StringBuffer buf = new StringBuffer(); for (int i=0; i!= length; i++) { int v = data[i] & 0xff; buf.append(digits.charAt(v >>4)); buf.append(digits.charAt(v & 0xf)); } return buf.toString(); } public static String toHex(byte[] data) { return toHex(data, data.length); } }

    Read the article

  • Des decryption returns empty

    - by Nilambari
    Hi, I am using Des.php for decryption. For few texts descript function returns Correct output in readable text format. For few... it just returns blank(empty.) After debugging in Des.php, i found that function _unpad($text) is returning false. The input $text is also still encoded. What could be the reason? Whenever decrypt function calls for _unpad($text) function, i am getting empty as results. Des.php resource: here

    Read the article

  • I am getting a Radix out of range exception on performing decryption

    - by user3672391
    I am generating a keypair and converting one of the same into string which later is inserted into the database using the following code: KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(2048); KeyPair generatedKeyPair = keyGen.genKeyPair(); PublicKey pubkey = generatedKeyPair.getPublic(); PrivateKey prvkey = generatedKeyPair.getPrivate(); System.out.println("My Public Key>>>>>>>>>>>"+pubkey); System.out.println("My Private Key>>>>>>>>>>>"+prvkey); String keyAsString = new BigInteger(prvkey.getEncoded()).toString(64); I then retrieve the string from the database and convert it back to the original key using the following code (where rst is my ResultSet): String keyAsString = rst.getString("privateKey").toString(); byte[] bytes = new BigInteger(keyAsString, 64).toByteArray(); //byte k[] = "HignDlPs".getBytes(); PKCS8EncodedKeySpec encodedKeySpec = new PKCS8EncodedKeySpec(bytes); KeyFactory rsaKeyFac = KeyFactory.getInstance("RSA"); PrivateKey privKey = rsaKeyFac.generatePrivate(encodedKeySpec); On using the privKey for RSA decryption, I get the following exception java.lang.NumberFormatException: Radix out of range at java.math.BigInteger.<init>(BigInteger.java:294) at com.util.SimpleFTPClient.downloadFile(SimpleFTPClient.java:176) at com.Action.FileDownload.processRequest(FileDownload.java:64) at com.Action.FileDownload.doGet(FileDownload.java:94) Please guide.

    Read the article

1 2 3 4 5 6 7 8 9 10 11  | Next Page >