Search Results

Search found 510 results on 21 pages for 'decrypt'.

Page 6/21 | < Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >

  • Encrypt URL in asp.net

    - by Zerotoinfinite
    Hi All, My site is in asp.net 3.5 and C#. I am sending link to my user through mail, now I want to send each user a specific URL. so instead of sending the clear text I want to send link with encrypted string URL, which I will decrypt on my home page. Like instead of www.mysite.aspx\mypage?userId=12 i'll send www.mysite.aspx\mypage?UserId=)@kasd12 and the same i'll decrypt on my page so that I'll get the userId = 12. Please let me know if my approach is correct and not and how can I encrypt & decrypt the string in simplest and easier manner. Thanks in advance.

    Read the article

  • using crypto++ on iphone sdk with pycrypto on app engine

    - by Joey
    Hi, I'm trying to encrypt http requests using crypto++ and decrypt them with pycrypto on the app engine server end. Using Arc4 encryption, I can successfully encrypt and decrypt on the iphone end but when I try decrypting on app engine, the result is garbled. I thought maybe it has something to do with the encoding of the NSString but am not certain. It's not clear to me if I need to call encode() on the cipher on the server end before decrypting, although that does seem to resolve a failure to decrypt involving ascii values. I have a separate post that delves a bit into this. Can anyone offer some advice? http://stackoverflow.com/questions/2794942/crypto-pycrypto-with-google-app-engine

    Read the article

  • Retrieving data from an encrypted text file?

    - by user
    Let's say I have a text file contains my data. data : ab bc de - encrypted data on text file : ba cb ed I want to find bc from text file, so I have to decrypt the text file with this code : SL:=TStringList.create; SL.LoadFromFile(textfile) SLtemp:=TStringList.create; for I := 0 to SL.Count - 1 do SLtemp.Add(ReverseString(SL[i])); //decrypt SL.Free; for I := 0 to SLtemp.Count - 1 do if SLtemp[i] = 'bc' then begin showmessage('found'); break; end; SLtemp.Free; I think my way is wasting resources. I have to load whole file to memory and decrypt them. I need some suggestions here to find quickly a specific line from an encrypted text. Thanks.

    Read the article

  • Encryption in PHP leaves unwanted characters

    - by MichaelH
    I have made an encryption function which encrypts a simple value and stores it in the database. Here is the code to encrypt and decrypt: public function encrypt($string){ $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB); $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND); $value = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $this->key256, $string, MCRYPT_MODE_ECB, $iv); $value = base64_encode($value); return $value; } public function decrypt($string){ $value = base64_decode($string); $value = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $this->key256, $value, MCRYPT_MODE_ECB); return $value; } When I encrypt a simple value such as 'Michael' and decrypt again, I get the value: Michael????????? Is there a reason I get all those question marks or a way to get rid of them?

    Read the article

  • To 'seal' or to 'wrap': that is the question ...

    - by Simon Thorpe
    If you follow this blog you will already have a good idea of what Oracle Information Rights Management (IRM) does. By encrypting documents Oracle IRM secures and tracks all copies of those documents, everywhere they are shared, stored and used, inside and outside your firewall. Unlike earlier encryption products authorized end users can transparently use IRM-encrypted documents within standard desktop applications such as Microsoft Office, Adobe Reader, Internet Explorer, etc. without first having to manually decrypt the documents. Oracle refers to this encryption process as 'sealing', and it is thanks to the freely available Oracle IRM Desktop that end users can transparently open 'sealed' documents within desktop applications without needing to know they are encrypted and without being able to save them out in unencrypted form. So Oracle IRM provides an amazing, unprecedented capability to secure and track every copy of your most sensitive information - even enabling end user access to be revoked long after the documents have been copied to home computers or burnt to CD/DVDs. But what doesn't it do? The main limitation of Oracle IRM (and IRM products in general) is format and platform support. Oracle IRM supports by far the broadest range of desktop applications and the deepest range of application versions, compared to other IRM vendors. This is important because you don't want to exclude sensitive business processes from being 'sealed' just because either the file format is not supported or users cannot upgrade to the latest version of Microsoft Office or Adobe Reader. But even the Oracle IRM Desktop can only open 'sealed' documents on Windows and does not for example currently support CAD (although this is coming in a future release). IRM products from other vendors are much more restrictive. To address this limitation Oracle has just made available the Oracle IRM Wrapper all-format, any-platform encryption/decryption utility. It uses the same core Oracle IRM web services and classification-based rights model to manually encrypt and decrypt files of any format on any Java-capable operating system. The encryption envelope is the same, and it uses the same role- and classification-based rights as 'sealing', but before you can use 'wrapped' files you must manually decrypt them. Essentially it is old-school manual encryption/decryption using the modern classification-based rights model of Oracle IRM. So if you want to share sensitive CAD documents, ZIP archives, media files, etc. with a partner, and you already have Oracle IRM, it's time to get 'wrapping'! Please note that the Oracle IRM Wrapper is made available as a free sample application (with full source code) and is not formally supported by Oracle. However it is informally supported by its author, Martin Lambert, who also created the widely-used Oracle IRM Hot Folder automated sealing application.

    Read the article

  • GPG Workflow in 11.04

    - by Ross Bearman
    At work we handle the transfer of small bits of sensitive data with GPG, usually posted on a secure internal website. Until Firefox 4 was released, we used FireGPG for inline decryption; however the IPC libraries that it relied upon were no longer present in FF4, making it unusable and it will no longer install in FF5. Currently I'm manually pasting the GPG blocks into a text file, then using the Nautilus context-menu plugin or the command line to decrypt the contents of the file. When we're handling large amount of these small files throughout the day this starts to become a real chore. I've looked around but can't seem to find much information on useful GPG clients in Ubuntu. A client that allowed me to paste in a GPG block and instantly decrypt it, and also paste in plaintext and easily encrypt it for multiple recipients would be ideal. So my question is does this exist? I can't seem to find anything about this with obvious searches on Google, so hopefully someone here can help, or offer an alternative workflow.

    Read the article

  • Execute encrypted files but don't let anybody read them.

    - by Stebi
    I want to provide a virtual machine image with an installed web application. The user should be able to boot the vm (don't login, just boot) and a webserver should start automatically. The point is I want to hide the (ruby) source code of the web application from everyone as there is no obfuscator for ruby. I thought I could use file system encryption to encrypt the directory with the sourcecode (or even a whole partition). But the webserver user must be able to read it automatically after booting. Nobody is allowed to login as the webserver user (or any other user) so no other can read the contents. My questions are now: Is this possible? Because I give away the whole vm everybody could mount its virtual discs and read them (except the encrypted one). Is it now possible to find the key the webserver user needs to decrypt the files and decrypt them manually? Or is it safe to give such a vm away? The problem is that everything needed to decrypt must be included somewhere in the vm else the webserver cannot start automatically. Maybe I'm completely wrong and you have another tip for me securing the source code.

    Read the article

  • Wireshark WPA 4-way handshake

    - by cYrus
    From this wiki page: WPA and WPA2 use keys derived from an EAPOL handshake to encrypt traffic. Unless all four handshake packets are present for the session you're trying to decrypt, Wireshark won't be able to decrypt the traffic. You can use the display filter eapol to locate EAPOL packets in your capture. I've noticed that the decryption works with (1, 2, 4) too, but not with (1, 2, 3). As far as I know the first two packets are enough, at least for what concern unicast traffic. Can someone please explain exactly how does Wireshark deal with that, in other words why does only the former sequence work, given that the fourth packet is just an acknowledgement? Also, is it guaranteed that the (1, 2, 4) will always work when (1, 2, 3, 4) works? Test case This is the gzipped handshake (1, 2, 4) and an ecrypted ARP packet (SSID: SSID, password: password) in base64 encoding: H4sICEarjU8AA2hhbmRzaGFrZS5jYXAAu3J400ImBhYGGPj/n4GhHkhfXNHr37KQgWEqAwQzMAgx 6HkAKbFWzgUMhxgZGDiYrjIwKGUqcW5g4Ldd3rcFQn5IXbWKGaiso4+RmSH+H0MngwLUZMarj4Rn S8vInf5yfO7mgrMyr9g/Jpa9XVbRdaxH58v1fO3vDCQDkCNv7mFgWMsAwXBHMoEceQ3kSMZbDFDn ITk1gBnJkeX/GDkRjmyccfus4BKl75HC2cnW1eXrjExNf66uYz+VGLl+snrF7j2EnHQy3JjDKPb9 3fOd9zT0TmofYZC4K8YQ8IkR6JaAT0zIJMjxtWaMmCEMdvwNnI5PYEYJYSTHM5EegqhggYbFhgsJ 9gJXy42PMx9JzYKEcFkcG0MJULYE2ZEGrZwHIMnASwc1GSw4mmH1JCCNQYEF7C7tjasVT+0/J3LP gie59HFL+5RDIdmZ8rGMEldN5s668eb/tp8vQ+7OrT9jPj/B7425QIGJI3Pft72dLxav8BefvcGU 7+kfABxJX+SjAgAA Decode with: $ base64 -d | gunzip > handshake.cap Run tshark to see if it correctly decrypt the ARP packet: $ tshark -r handshake.cap -o wlan.enable_decryption:TRUE -o wlan.wep_key1:wpa-pwd:password:SSID It should print: 1 0.000000 D-Link_a7:8e:b4 - HonHaiPr_22:09:b0 EAPOL Key 2 0.006997 HonHaiPr_22:09:b0 - D-Link_a7:8e:b4 EAPOL Key 3 0.038137 HonHaiPr_22:09:b0 - D-Link_a7:8e:b4 EAPOL Key 4 0.376050 ZyxelCom_68:3a:e4 - HonHaiPr_22:09:b0 ARP 192.168.1.1 is at 00:a0:c5:68:3a:e4

    Read the article

  • How to securely control access to a backend key server?

    - by andy
    I need to securely encrypt data in my database so that if the database is dumped, hackers are unable to decrypt the data. I'm planning on creating a simple key server on a different machine, and allowing the DB server access to it (restricted by IP address on the key server to permit the DB server). The key server would contain the key required to encrypt/decrypt data. However, if a hacker were able to get a shell on the DB server, they could request the key from the key server and therefore decrypt the data in the database. How could I prevent this (assuming all firewalls are in place, DB is not connected directly to the internet, etc)? i.e. is there some method I could use that could secure a request from the DB server to the key server so that even if a hacker had a shell on the DB server they'd be unable to make those same requests? Signed requests from the DB server could make issuing these requests less trivial - I suppose that'd help increase the amount of time it'd take to compromise the key server, something a hacker probably wouldn't have much of. As far as I can see, if someone can get a shell on the DB server everything's lost anyway. This could be mitigated by using one key per data item in the DB so at least there's not a single "master" key, but multiple keys that the hacker would need to access. What would be a secure method of ensuring requests from the DB server to the key server were authentic and could be trusted?

    Read the article

  • String encryption in C# and Objective c

    - by nbojja
    Hi All, I am building a iPhone app which uses c# web services. My c# web services takes user details and validates against my DB and returns xml files. So Now the issue is how to encrypt user details(username and password are 10chars each) in objective c and decrypt in C#. I am very new to cryptography, which method is the best. will it be possible to encrypt in Objective c and Decrypt in C#. thanks..

    Read the article

  • Java Encryption issue

    - by r1k0
    I am using PBE encryption to encrypt and decrypt some text on an Android application but I get the BadPaddingException: with the "pad block corrupted" message when I use the wrong private key to decrypt the text. My question, since I am not well versed with encryption in Java, is if this is the normal behavior of the encryption API, because I need to do some logic in the case when the wrong key is entered, but I do not know the private key, nor do I store it anywhere (storing just the encrypted and decrypted check text). Thanks, Mihai

    Read the article

  • Text Obfuscation using base64_encode()

    - by user271619
    I'm playing around with encrypt/decrypt coding in php. Interesting stuff! However, I'm coming across some issues involving what text gets encrypted into. Here's 2 functions that encrypt and decrypt a string. It uses an Encryption Key, which I set as something obscure. I actually got this from a php book. I modified it slightly, but not to change it's main goal. I created a small example below that anyone can test. But, I notice that some characters show up as the "encrypted" string. Characters like "=" and "+". Sometimes I pass this encrypted string via the url. Which may not quite make it to my receiving scripts. I'm guessing the browser does something to the string if certain characters are seen. I'm really only guessing. is there another function I can use to ensure the browser doesn't touch the string? or does anyone know enough php bas64_encode() to disallow certain characters from being used? I'm really not going to expect the latter as a possibility. But, I'm sure there's a work-around. enjoy the code, whomever needs it! define('ENCRYPTION_KEY', "sjjx6a"); function encrypt($string) { $result = ''; for($i=0; $i<strlen($string); $i++) { $char = substr($string, $i, 1); $keychar = substr(ENCRYPTION_KEY, ($i % strlen(ENCRYPTION_KEY))-1, 1); $char = chr(ord($char)+ord($keychar)); $result.=$char; } return base64_encode($result)."/".rand(); } function decrypt($string){ $exploded = explode("/",$string); $string = $exploded[0]; $result = ''; $string = base64_decode($string); for($i=0; $i<strlen($string); $i++) { $char = substr($string, $i, 1); $keychar = substr(ENCRYPTION_KEY, ($i % strlen(ENCRYPTION_KEY))-1, 1); $char = chr(ord($char)-ord($keychar)); $result.=$char; } return $result; } echo $encrypted = encrypt("reaplussign.jpg"); echo "<br>"; echo decrypt($encrypted);

    Read the article

  • Using mcrypt to pass data across a webservice is failing

    - by adam
    Hi I'm writing an error handler script which encrypts the error data (file, line, error, message etc) and passes the serialized array as a POST variable (using curl) to a script which then logs the error in a central db. I've tested my encrypt/decrypt functions in a single file and the data is encrypted and decrypted fine: define('KEY', 'abc'); define('CYPHER', 'blowfish'); define('MODE', 'cfb'); function encrypt($data) { $td = mcrypt_module_open(CYPHER, '', MODE, ''); $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND); mcrypt_generic_init($td, KEY, $iv); $crypttext = mcrypt_generic($td, $data); mcrypt_generic_deinit($td); return $iv.$crypttext; } function decrypt($data) { $td = mcrypt_module_open(CYPHER, '', MODE, ''); $ivsize = mcrypt_enc_get_iv_size($td); $iv = substr($data, 0, $ivsize); $data = substr($data, $ivsize); if ($iv) { mcrypt_generic_init($td, KEY, $iv); $data = mdecrypt_generic($td, $data); } return $data; } echo "<pre>"; $data = md5(''); echo "Data: $data\n"; $e = encrypt($data); echo "Encrypted: $e\n"; $d = decrypt($e); echo "Decrypted: $d\n"; Output: Data: d41d8cd98f00b204e9800998ecf8427e Encrypted: ê÷#¯KžViiÖŠŒÆÜ,ÑFÕUW£´Œt?†÷>c×åóéè+„N Decrypted: d41d8cd98f00b204e9800998ecf8427e The problem is, when I put the encrypt function in my transmit file (tx.php) and the decrypt in my recieve file (rx.php), the data is not fully decrypted (both files have the same set of constants for key, cypher and mode). Data before passing: a:4:{s:3:"err";i:1024;s:3:"msg";s:4:"Oops";s:4:"file";s:46:"/Applications/MAMP/htdocs/projects/txrx/tx.php";s:4:"line";i:80;} Data decrypted: Mª4:{s:3:"err";i:1024@7OYªç`^;g";s:4:"Oops";s:4:"file";sôÔ8F•Ópplications/MAMP/htdocs/projects/txrx/tx.php";s:4:"line";i:80;} Note the random characters in the middle. My curl is fairly simple: $ch = curl_init($url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, 'data=' . $data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $output = curl_exec($ch); Things I suspect could be causing this: Encoding of the curl request Something to do with mcrypt padding missing bytes I've been staring at it too long and have missed something really really obvious If I turn off the crypt functions (so the transfer tx-rx is unencrypted) the data is received fine. Any and all help much appreciated! Thanks, Adam

    Read the article

  • libmcrypt and MS Visual C++

    - by macki
    Has anyone tried using libmcrypt and visual c++? I was trying to use Crypto++ but it seems not fully compatible - and I need to decrypt data encrypted in PHP using linux libmcrypt. I found only cygwin version of libmcrypt but no .lib files or header. I'm using RIJNDAEL_128 - maybe there is easier way to decrypt it in Visual C++? Thanks

    Read the article

  • How can I encrypt a querystring in asp.net?

    - by Dave Haynes
    I need to encrypt and decrypt a querystring in ASP.NET. The querystring might look something like this: http://www.mysite.com/report.aspx?id=12345&year=2008 How do I go about encrypting the entire querystring so that it looks something like the following? http://www.mysite.com/report.aspx?crypt=asldjfaf32as98df8a And then, of course, how to I decrypt it? What's the best encryption to use for something like this? TripleDES?

    Read the article

  • What is the best nuclear missile crypto system?

    - by The Rook
    You are on a submarine and there is an encrypted message that you want to read. Two people must use their keys at the same time in order to obtain the plain text. What is best cryptographic primitive to use? Are the following two implementations suitable? plain_text=decrypt(Key1 XOR key2,ciper_text,IV) plain_text=decrypt(Key1,rc4_encrypt(key2,ciper_text,IV2),IV1)

    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

  • Oh no! My padding's invalid!

    - by Simon Cooper
    Recently, I've been doing some work involving cryptography, and encountered the standard .NET CryptographicException: 'Padding is invalid and cannot be removed.' Searching on StackOverflow produces 57 questions concerning this exception; it's a very common problem encountered. So I decided to have a closer look. To test this, I created a simple project that decrypts and encrypts a byte array: // create some random data byte[] data = new byte[100]; new Random().NextBytes(data); // use the Rijndael symmetric algorithm RijndaelManaged rij = new RijndaelManaged(); byte[] encrypted; // encrypt the data using a CryptoStream using (var encryptor = rij.CreateEncryptor()) using (MemoryStream encryptedStream = new MemoryStream()) using (CryptoStream crypto = new CryptoStream( encryptedStream, encryptor, CryptoStreamMode.Write)) { crypto.Write(data, 0, data.Length); encrypted = encryptedStream.ToArray(); } byte[] decrypted; // and decrypt it again using (var decryptor = rij.CreateDecryptor()) using (CryptoStream crypto = new CryptoStream( new MemoryStream(encrypted), decryptor, CryptoStreamMode.Read)) { byte[] decrypted = new byte[data.Length]; crypto.Read(decrypted, 0, decrypted.Length); } Sure enough, I got exactly the same CryptographicException when trying to decrypt the data even in this simple example. Well, I'm obviously missing something, if I can't even get this single method right! What does the exception message actually mean? What am I missing? Well, after playing around a bit, I discovered the problem was fixed by changing the encryption step to this: // encrypt the data using a CryptoStream using (var encryptor = rij.CreateEncryptor()) using (MemoryStream encryptedStream = new MemoryStream()) { using (CryptoStream crypto = new CryptoStream( encryptedStream, encryptor, CryptoStreamMode.Write)) { crypto.Write(data, 0, data.Length); } encrypted = encryptedStream.ToArray(); } Aaaah, so that's what the problem was. The CryptoStream wasn't flushing all it's data to the MemoryStream before it was being read, and closing the stream causes it to flush everything to the backing stream. But why does this cause an error in padding? Cryptographic padding All symmetric encryption algorithms (of which Rijndael is one) operates on fixed block sizes. For Rijndael, the default block size is 16 bytes. This means the input needs to be a multiple of 16 bytes long. If it isn't, then the input is padded to 16 bytes using one of the padding modes. This is only done to the final block of data to be encrypted. CryptoStream has a special method to flush this final block of data - FlushFinalBlock. Calling Stream.Flush() does not flush the final block, as you might expect. Only by closing the stream or explicitly calling FlushFinalBlock is the final block, with any padding, encrypted and written to the backing stream. Without this call, the encrypted data is 16 bytes shorter than it should be. If this final block wasn't written, then the decryption gets to the final 16 bytes of the encrypted data and tries to decrypt it as the final block with padding. The end bytes don't match the padding scheme it's been told to use, therefore it throws an exception stating what is wrong - what the decryptor expects to be padding actually isn't, and so can't be removed from the stream. So, as well as closing the stream before reading the result, an alternative fix to my encryption code is the following: // encrypt the data using a CryptoStream using (var encryptor = rij.CreateEncryptor()) using (MemoryStream encryptedStream = new MemoryStream()) using (CryptoStream crypto = new CryptoStream( encryptedStream, encryptor, CryptoStreamMode.Write)) { crypto.Write(data, 0, data.Length); // explicitly flush the final block of data crypto.FlushFinalBlock(); encrypted = encryptedStream.ToArray(); } Conclusion So, if your padding is invalid, make sure that you close or call FlushFinalBlock on any CryptoStream performing encryption before you access the encrypted data. Flush isn't enough. Only then will the final block be present in the encrypted data, allowing it to be decrypted successfully.

    Read the article

  • Caesar Cipher Program In C++ [migrated]

    - by xaliap81
    I am trying to write a caesar cipher program in c++. This is my codes template: int chooseKEY (){ //choose key shift from 1-26 } void encrypt (char * w, char *e, int key) { //Encryption function, *w is the text in the beginning, the *e is the encrypted text //Encryption in being made only in letters noy in numbers and punctuations // *e = *w + key } void decrypt (char * e, char *w, int key) { // Decryption function, *e is the text in the beginning, the *w is the decrypted text //Dencryption in being made only in letters no numbers and punctuations // *w = *e - key } void Caesar (char * inputFile, char * outputFile, int key, int mode) { // Read the inputfile which contains some data. If mode ==1 then the data is being //encrypted else if mode == 0 the data is being decrypted and is being written in //the output file } void main() { // call the Caesar function } The program has four functions, chooseKey function have to return an int as a shift key from 1-26. Encrypt function has three parameters, *w is the text in the beginning, *e is the encrypted text and the key is from the choosekey function.For encryption : Only letters have to be encrypted not numbers or punctuation and the letters are counting cyclic. Decrypt function has three parameters *e is the encrypted text, *w is the beginning text and the key. Caesar function has four parameters, inputfile which is the file that contains the beginning text, output file which contains the encrypted text, the key and the mode (if mode==1) encryption, (mode ==0) decryption. This is my sample code: #include <iostream> #include <fstream> using namespace std; int chooseKey() { int key_number; cout << "Give a number from 1-26: "; cin >> key_number; while(key_number<1 || key_number>26) { cout << "Your number have to be from 1-26.Retry: "; cin >> key_number; } return key_number; } void encryption(char *w, char *e, int key){ char *ptemp = w; while(*ptemp){ if(isalpha(*ptemp)){ if(*ptemp>='a'&&*ptemp<='z') { *ptemp-='a'; *ptemp+=key; *ptemp%=26; *ptemp+='A'; } } ptemp++; } w=e; } void decryption (char *e, char *w, int key){ char *ptemp = e; while(*ptemp){ if(isalpha(*ptemp)) { if(*ptemp>='A'&&*ptemp<='Z') { *ptemp-='A'; *ptemp+=26-key; *ptemp%=26; *ptemp+='a'; } } ptemp++; } e=w; } void Caesar (char *inputFile, char *outputFile, int key, int mode) { ifstream input; ofstream output; char buf, buf1; input.open(inputFile); output.open(outputFile); buf=input.get(); while(!input.eof()) { if(mode == 1){ encryption(&buf, &buf1, key); }else{ decryption(&buf1, &buf, key); } output << buf; buf=input.get(); } input.close(); output.close(); } int main(){ int key, mode; key = chooseKey(); cout << "1 or 0: "; cin >> mode; Caesar("test.txt","coded.txt",key,mode); system("pause"); } I am trying to run the code and it is being crashed (Debug Assertion Failed). I think the problem is somewhere inside Caesar function.How to call the encrypt and decrypt functions. But i don't know what exactly is. Any ideas?

    Read the article

  • Encryption is hard: AES encryption to Hex

    - by Rob Cameron
    So, I've got an app at work that encrypts a string using ColdFusion. ColdFusion's bulit-in encryption helpers make it pretty simple: encrypt('string_to_encrypt','key','AES','HEX') What I'm trying to do is use Ruby to create the same encrypted string as this ColdFusion script is creating. Unfortunately encryption is the most confusing computer science subject known to man. I found a couple helper methods that use the openssl library and give you a really simple encryption/decryption method. Here's the resulting string: "\370\354D\020\357A\227\377\261G\333\314\204\361\277\250" Which looks unicode-ish to me. I've tried several libraries to convert this to hex but they all say it contains invalid characters. Trying to unpack it results in this: string = "\370\354D\020\357A\227\377\261G\333\314\204\361\277\250" string.unpack('U') ArgumentError: malformed UTF-8 character from (irb):19:in `unpack' from (irb):19 At the end of the day it's supposed to look like this (the output of the ColdFusion encrypt method): F8E91A689565ED24541D2A0109F201EF Of course that's assuming that all the padding, initialization vectors, salts, cypher types and a million other possible differences all line up. Here's the simple script I'm using to encrypt/decrypt: def aes(m,k,t) (aes = OpenSSL::Cipher::Cipher.new('aes-256-cbc').send(m)).key = Digest::SHA256.digest(k) aes.update(t) << aes.final end def encrypt(key, text) aes(:encrypt, key, text) end def decrypt(key, text) aes(:decrypt, key, text) end Any help? Maybe just a simple option I can pass to OpenSSL::Cipher::Cipher that will tell it to hex-encode the final string?

    Read the article

  • Invalid length for a Base-64 char array.

    - by Code Sherpa
    As the title says, I am getting: Invalid length for a Base-64 char array. I have read about this problem on here and it seems that the suggestion is to store ViewState in SQL if it is large. I am using a wizard with a good deal of data collection so chances are my ViewSate is large. But, before I turn to the "store-in-DB" solution, maybe somebody can take a look and tell me if I have other options? I construct the email for delivery using the below method: public void SendEmailAddressVerificationEmail(string userName, string to) { string msg = "Please click on the link below or paste it into a browser to verify your email account.<BR><BR>" + "<a href=\"" + _configuration.RootURL + "Accounts/VerifyEmail.aspx?a=" + userName.Encrypt("verify") + "\">" + _configuration.RootURL + "Accounts/VerifyEmail.aspx?a=" + userName.Encrypt("verify") + "</a>"; SendEmail(to, "", "", "Account created! Email verification required.", msg); } The Encrypt method looks like this: public static string Encrypt(string clearText, string Password) { byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(clearText); PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); byte[] encryptedData = Encrypt(clearBytes, pdb.GetBytes(32), pdb.GetBytes(16)); return Convert.ToBase64String(encryptedData); } On the receiving end, the VerifyEmail.aspx.cs page has the line: string username = Cryptography.Decrypt(_webContext.UserNameToVerify, "verify"); And the decrypt method looks like: public static string Decrypt(string cipherText, string password) { **// THE ERROR IS THROWN HERE!!** byte[] cipherBytes = Convert.FromBase64String(cipherText); Can this error be remedied with a code fix or must I store ViewState in the database? Thanks in advance.

    Read the article

  • How to resolve deprecation warnings for OpenSSL::Cipher::Cipher#encrypt

    - by Olly
    I've just upgraded my Mac to Snow Leopard and got my Rails environment up and running. The only difference -- OSX aside -- with my previous install is that I'm now running ruby 1.8.7 (2008-08-11 patchlevel 72) [universal-darwin10.0] (Snow Leopard default) rather than 1.8.6. I'm now seeing deprecation warnings relating to OpenSSL when I run my code: warning: argumtents for OpenSSL::Cipher::Cipher#encrypt and OpenSSL::Cipher::Cipher#decrypt were deprecated; use OpenSSL::Cipher::Cipher#pkcs5_keyivgen to derive key and IV Example of my code which is causing these warnings (it decodes an encrypted string) on line 4: 1. def decrypt(data) 2. encryptor = OpenSSL::Cipher::Cipher.new('DES-EDE3-CBC') 3. key = "my key" 4. encryptor.decrypt(key) 5. text = encryptor.update(data) 6. text << encryptor.final 7. end I'm struggling to understand how I can resolve this, and Google isn't really helping. Should I try and downgrade to Ruby 1.8.6 (and if so, what's the best way of doing this?), should I try and just hide the warnings (bury my head in the sand?!) or is there an easy fix I can apply in the code?

    Read the article

  • Error "Input length must be multiple of 8 when decrypting with padded cipher"

    - by Ross Peoples
    I am trying to move a project from C# to Java for a learning exercise. I am still very new to Java, but I have a TripleDES class in C# that encrypts strings and returns a string value of the encrypted byte array. Here is my C# code: using System; using System.IO; using System.Collections.Generic; using System.Security.Cryptography; using System.Text; namespace tDocc.Classes { /// <summary> /// Triple DES encryption class /// </summary> public static class TripleDES { private static byte[] key = { 110, 32, 73, 24, 125, 66, 75, 18, 79, 150, 211, 122, 213, 14, 156, 136, 171, 218, 119, 240, 81, 142, 23, 4 }; private static byte[] iv = { 25, 117, 68, 23, 99, 78, 231, 219 }; /// <summary> /// Encrypt a string to an encrypted byte array /// </summary> /// <param name="plainText">Text to encrypt</param> /// <returns>Encrypted byte array</returns> public static byte[] Encrypt(string plainText) { UTF8Encoding utf8encoder = new UTF8Encoding(); byte[] inputInBytes = utf8encoder.GetBytes(plainText); TripleDESCryptoServiceProvider tdesProvider = new TripleDESCryptoServiceProvider(); ICryptoTransform cryptoTransform = tdesProvider.CreateEncryptor(key, iv); MemoryStream encryptedStream = new MemoryStream(); CryptoStream cryptStream = new CryptoStream(encryptedStream, cryptoTransform, CryptoStreamMode.Write); cryptStream.Write(inputInBytes, 0, inputInBytes.Length); cryptStream.FlushFinalBlock(); encryptedStream.Position = 0; byte[] result = new byte[encryptedStream.Length]; encryptedStream.Read(result, 0, (int)encryptedStream.Length); cryptStream.Close(); return result; } /// <summary> /// Decrypt a byte array to a string /// </summary> /// <param name="inputInBytes">Encrypted byte array</param> /// <returns>Decrypted string</returns> public static string Decrypt(byte[] inputInBytes) { UTF8Encoding utf8encoder = new UTF8Encoding(); TripleDESCryptoServiceProvider tdesProvider = new TripleDESCryptoServiceProvider(); ICryptoTransform cryptoTransform = tdesProvider.CreateDecryptor(key, iv); MemoryStream decryptedStream = new MemoryStream(); CryptoStream cryptStream = new CryptoStream(decryptedStream, cryptoTransform, CryptoStreamMode.Write); cryptStream.Write(inputInBytes, 0, inputInBytes.Length); cryptStream.FlushFinalBlock(); decryptedStream.Position = 0; byte[] result = new byte[decryptedStream.Length]; decryptedStream.Read(result, 0, (int)decryptedStream.Length); cryptStream.Close(); UTF8Encoding myutf = new UTF8Encoding(); return myutf.GetString(result); } /// <summary> /// Decrypt an encrypted string /// </summary> /// <param name="text">Encrypted text</param> /// <returns>Decrypted string</returns> public static string DecryptText(string text) { if (text == "") { return text; } return Decrypt(Convert.FromBase64String(text)); } /// <summary> /// Encrypt a string /// </summary> /// <param name="text">Unencrypted text</param> /// <returns>Encrypted string</returns> public static string EncryptText(string text) { if (text == "") { return text; } return Convert.ToBase64String(Encrypt(text)); } } /// <summary> /// Random number generator /// </summary> public static class RandomGenerator { /// <summary> /// Generate random number /// </summary> /// <param name="length">Number of randomizations</param> /// <returns>Random number</returns> public static int GenerateNumber(int length) { byte[] randomSeq = new byte[length]; new RNGCryptoServiceProvider().GetBytes(randomSeq); int code = Environment.TickCount; foreach (byte b in randomSeq) { code += (int)b; } return code; } } /// <summary> /// Hash generator class /// </summary> public static class Hasher { /// <summary> /// Hash type /// </summary> public enum eHashType { /// <summary> /// MD5 hash. Quick but collisions are more likely. This should not be used for anything important /// </summary> MD5 = 0, /// <summary> /// SHA1 hash. Quick and secure. This is a popular method for hashing passwords /// </summary> SHA1 = 1, /// <summary> /// SHA256 hash. Slower than SHA1, but more secure. Used for encryption keys /// </summary> SHA256 = 2, /// <summary> /// SHA348 hash. Even slower than SHA256, but offers more security /// </summary> SHA348 = 3, /// <summary> /// SHA512 hash. Slowest but most secure. Probably overkill for most applications /// </summary> SHA512 = 4, /// <summary> /// Derrived from MD5, but only returns 12 digits /// </summary> Digit12 = 5 } /// <summary> /// Hashes text using a specific hashing method /// </summary> /// <param name="text">Input text</param> /// <param name="hash">Hash method</param> /// <returns>Hashed text</returns> public static string GetHash(string text, eHashType hash) { if (text == "") { return text; } if (hash == eHashType.MD5) { MD5CryptoServiceProvider hasher = new MD5CryptoServiceProvider(); return ByteToHex(hasher.ComputeHash(Encoding.ASCII.GetBytes(text))); } else if (hash == eHashType.SHA1) { SHA1Managed hasher = new SHA1Managed(); return ByteToHex(hasher.ComputeHash(Encoding.ASCII.GetBytes(text))); } else if (hash == eHashType.SHA256) { SHA256Managed hasher = new SHA256Managed(); return ByteToHex(hasher.ComputeHash(Encoding.ASCII.GetBytes(text))); } else if (hash == eHashType.SHA348) { SHA384Managed hasher = new SHA384Managed(); return ByteToHex(hasher.ComputeHash(Encoding.ASCII.GetBytes(text))); } else if (hash == eHashType.SHA512) { SHA512Managed hasher = new SHA512Managed(); return ByteToHex(hasher.ComputeHash(Encoding.ASCII.GetBytes(text))); } else if (hash == eHashType.Digit12) { MD5CryptoServiceProvider hasher = new MD5CryptoServiceProvider(); string newHash = ByteToHex(hasher.ComputeHash(Encoding.ASCII.GetBytes(text))); return newHash.Substring(0, 12); } return ""; } /// <summary> /// Generates a hash based on a file's contents. Used for detecting changes to a file and testing for duplicate files /// </summary> /// <param name="info">FileInfo object for the file to be hashed</param> /// <param name="hash">Hash method</param> /// <returns>Hash string representing the contents of the file</returns> public static string GetHash(FileInfo info, eHashType hash) { FileStream hashStream = new FileStream(info.FullName, FileMode.Open, FileAccess.Read); string hashString = ""; if (hash == eHashType.MD5) { MD5CryptoServiceProvider hasher = new MD5CryptoServiceProvider(); hashString = ByteToHex(hasher.ComputeHash(hashStream)); } else if (hash == eHashType.SHA1) { SHA1Managed hasher = new SHA1Managed(); hashString = ByteToHex(hasher.ComputeHash(hashStream)); } else if (hash == eHashType.SHA256) { SHA256Managed hasher = new SHA256Managed(); hashString = ByteToHex(hasher.ComputeHash(hashStream)); } else if (hash == eHashType.SHA348) { SHA384Managed hasher = new SHA384Managed(); hashString = ByteToHex(hasher.ComputeHash(hashStream)); } else if (hash == eHashType.SHA512) { SHA512Managed hasher = new SHA512Managed(); hashString = ByteToHex(hasher.ComputeHash(hashStream)); } hashStream.Close(); hashStream.Dispose(); hashStream = null; return hashString; } /// <summary> /// Converts a byte array to a hex string /// </summary> /// <param name="data">Byte array</param> /// <returns>Hex string</returns> public static string ByteToHex(byte[] data) { StringBuilder builder = new StringBuilder(); foreach (byte hashByte in data) { builder.Append(string.Format("{0:X1}", hashByte)); } return builder.ToString(); } /// <summary> /// Converts a hex string to a byte array /// </summary> /// <param name="hexString">Hex string</param> /// <returns>Byte array</returns> public static byte[] HexToByte(string hexString) { byte[] returnBytes = new byte[hexString.Length / 2]; for (int i = 0; i <= returnBytes.Length - 1; i++) { returnBytes[i] = byte.Parse(hexString.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber); } return returnBytes; } } } And her is what I've got for Java code so far, but I'm getting the error "Input length must be multiple of 8 when decrypting with padded cipher" when I run the test on this: import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import javax.crypto.Cipher; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import com.tdocc.utils.Base64; public class TripleDES { private static byte[] keyBytes = { 110, 32, 73, 24, 125, 66, 75, 18, 79, (byte)150, (byte)211, 122, (byte)213, 14, (byte)156, (byte)136, (byte)171, (byte)218, 119, (byte)240, 81, (byte)142, 23, 4 }; private static byte[] ivBytes = { 25, 117, 68, 23, 99, 78, (byte)231, (byte)219 }; public static String encryptText(String plainText) { try { if (plainText.isEmpty()) return plainText; return Base64.decode(TripleDES.encrypt(plainText)).toString(); } catch (Exception e) { e.printStackTrace(); } return null; } public static byte[] encrypt(String plainText) throws InvalidKeyException, InvalidAlgorithmParameterException, NoSuchPaddingException { try { final SecretKey key = new SecretKeySpec(keyBytes, "DESede"); final IvParameterSpec iv = new IvParameterSpec(ivBytes); final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key, iv); final byte[] plainTextBytes = plainText.getBytes("utf-8"); final byte[] cipherText = cipher.doFinal(plainTextBytes); return cipherText; } catch (Exception e) { e.printStackTrace(); } return null; } public static String decryptText(String message) { try { if (message.isEmpty()) return message; else return TripleDES.decrypt(message.getBytes()); } catch (Exception e) { e.printStackTrace(); } return null; } public static String decrypt(byte[] message) { try { final SecretKey key = new SecretKeySpec(keyBytes, "DESede"); final IvParameterSpec iv = new IvParameterSpec(ivBytes); final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, key, iv); final byte[] plainText = cipher.doFinal(message); return plainText.toString(); } catch (Exception e) { e.printStackTrace(); } return null; } }

    Read the article

  • Encryption in Java & Flex

    - by Jef
    I want tp encrypt and decrypt string, with defined salt. But the result must be same if the code run in java and adobe flex. The main goal is: the app in adobe flex will be generate a string that can be decrypt in server using java. I use this flex library http://crypto.hurlant.com/demo/ Try to 'Secret Key' Tab. I want to use AES Encryption, 'CBC' or 'PKCS5'. var k:String = "1234567890123456"; var kdata:ByteArray = Hex.toArray(k); var txt:String = "hello"; var data:ByteArray = Hex.toArray(Hex.fromString(txt));; var name:String = "simple-aes-cbc"; var pad:IPad =new PKCS5(); var mode:ICipher = Crypto.getCipher(name, kdata, pad); pad.setBlockSize(mode.getBlockSize()); mode.encrypt(data); encrypted.text=Hex.fromArray(data); trace(Hex.fromArray(data)); And here is the code in java String plaintext = "hello"; String key = "1234567890123456"; SecretKey keyspec = new SecretKeySpec(key.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE,keyspec); byte[] encrypted = cipher.doFinal(plaintext.getBytes()); BASE64Encoder base64 = new BASE64Encoder(); String encodedString = base64.encode(encrypted); System.out.println(encodedString); Why the result is not same? Can you guys provide the sample with the same result both of java and flex (encrypt and decrypt)? And if I want to change the paramater, for example, from cbc to ebc, which line that need to be changed? Thanks!

    Read the article

  • General String Encryption in .NET

    - by cryptospin
    I am looking for a general string encryption class in .NET. (Not to be confused with the 'SecureString' class.) I have started to come up with my own class, but thought there must be a .NET class that already allows you to encrypt/decrypt strings of any encoding with any Cryptographic Service Provider. Public Class SecureString Private key() As Byte Private iv() As Byte Private m_SecureString As String Public ReadOnly Property Encrypted() As String Get Return m_SecureString End Get End Property Public ReadOnly Property Decrypted() As String Get Return Decrypt(m_SecureString) End Get End Property Public Sub New(ByVal StringToSecure As String) If StringToSecure Is Nothing Then StringToSecure = "" m_SecureString = Encrypt(StringToSecure) End Sub Private Function Encrypt(ByVal StringToEncrypt As String) As String Dim result As String = "" Dim bytes() As Byte = Text.Encoding.UTF8.GetBytes(StringToEncrypt) Using provider As New AesCryptoServiceProvider() With provider .Mode = CipherMode.CBC .GenerateKey() .GenerateIV() key = .Key iv = .IV End With Using ms As New IO.MemoryStream Using cs As New CryptoStream(ms, provider.CreateEncryptor(), CryptoStreamMode.Write) cs.Write(bytes, 0, bytes.Length) cs.FlushFinalBlock() End Using result = Convert.ToBase64String(ms.ToArray()) End Using End Using Return result End Function Private Function Decrypt(ByVal StringToDecrypt As String) As String Dim result As String = "" Dim bytes() As Byte = Convert.FromBase64String(StringToDecrypt) Using provider As New AesCryptoServiceProvider() Using ms As New IO.MemoryStream Using cs As New CryptoStream(ms, provider.CreateDecryptor(key, iv), CryptoStreamMode.Write) cs.Write(bytes, 0, bytes.Length) cs.FlushFinalBlock() End Using result = Text.Encoding.UTF8.GetString(ms.ToArray()) End Using End Using Return result End Function End Class

    Read the article

< Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >