I have an issue with an API that requires me to run a BASE64 and MD5 of a string. While a JAVASCRIPT code I created works well with this API, I need it in PHP, and I get the worng answer.   While testing the issue, I came to a conclusion that the issue is with the way the base64_encode function works in PHP, differs, and that creates the problem. I am attaching a code that will demostrate it  var CryptoJS = require("crypto-js"); var testStr = 'hello world!'; console.log(String(CryptoJS.SHA256(testStr))); # outputs 7509e5bda0c762d2bac7f90d758b5b2263fa01ccbc542ab5e3df163be08e6ca9 console.log(CryptoJS.enc.Base64.stringify( CryptoJS.SHA256(testStr) )); # outputs dQnlvaDHYtK6x/kNdYtbImP6Acy8VCq1498WO+CObKk=   &lt;?php $testStr = 'hello world!'; echo hash('sha256', $testStr); # outputs 7509e5bda0c762d2bac7f90d758b5b2263fa01ccbc542ab5e3df163be08e6ca9 echo '&lt;br /&gt;'; echo base64_encode(hash('sha256', $testStr)); # outputs NzUwOWU1YmRhMGM3NjJkMmJhYzdmOTBkNzU4YjViMjI2M2ZhMDFjY2JjNTQyYWI1ZTNkZjE2M2JlMDhlNmNhOQ==   I need the PHP code to output the same BASE64 result as the JS code. Can you please clarify what I'm doing wrong, and how can I fix it?
18799
I have a PHP script that can encode a PNG image to a Base64 string.  I'd like to do the same thing using JavaScript. I know how to open files, but I'm not sure how to do the encoding. I'm not used to working with binary data.
53551
Some of my script are using different encoding, and when I try to combine them, this has becom an issue.  But I can't change the encoding they use, instead I want to change the encodig of the result from script A, and use it as parameter in script B.   So: is there any simple way to change a string from UTF-8 to ISO-88591 in PHP? I have looked at utf_encode and _decode, but they doesn't do what i want. Why doesn't there exsist any "utf2iso()"-function, or similar?  I don't think I have characters that can't be written in ISO-format, so that shouldn't be an huge issue.
43371
PHP has the habit of evaluating (int)0 and (string)"0" as empty when using the empty() function. This can have unintended results if you expect numerical or string values of 0. How can I "fix" it to only return true to empty objects, arrays, strings, etc?
75495
Apparently a lot of people complain that they only see random letters and characters:    My biggest problem is that I can't reproduce the problem on ANY of my devices! Not on my Windows XP laptop, not on my Windows 7 laptop, not on my Android phone or my iPod Touch. It doesn't matter which browser I'm using. The only time I see the problem myself is when I try to share one of my blog posts on Google+, because the blog description then appears in strange characters.  So, first of all I need to find a way to reproduce the problem somehow. Otherwise I won't be able to see if what I did fixed the problem or not.  I did everything that @toscho recommended, but nothing helped.  Did anybody ever run into a similar problem or would you know where I could start to look for the problem?  Edit: I contacted my webhost. They couldn't reproduce the problem, just like me. They said that they have enabled gzip compression on their servers. They suggested turning off one plugin after another to see what happens, but as I can't reproduce the problem, I can't do that. Please help!  More and more readers are complaining about this problem. Most of them just need to refresh the page or wait a few minutes and then the site loads normally, but I'm still using a lot of traffic because of that.  EDIT 2: The W3 Total Cache Plugin FAQ says: I see garbage characters instead of the normal web site, what's going on here?  If a theme or it's files use the call php_flush() or function flush() that will interfere with the plugins normal operation; making the plugin send cached files before essential operations have finished. The flush() call is no longer necessary and should be removed.  I am pretty sure that none of my code has this call anywhere, but I'm not 100% sure. Is there any way to find out other than searching through millions of characters in all of my files?
112121
I am new to PHP programming and trying to grasp the idea of hashing and encryption for protecting passwords, credit card details and such. I've done a lot of reading about MD5 which I think I understand the basics of now. I've seen places recommending that I use SHA2, which I don't understand how to implement.   Back to my question. I can understand how a script can tell if a password is correct or not by hashing the password and comparing the value against the hashed one in the database. My problem occurs when trying to understand salts. If I have a dynamic salt such as the date (yes, I have heard its a bad one to use), how does the script know that a password is correct because the salt will be different for the entered password and the one stored in the database.  For example: Say the original password was created on the 21/02/2011:   unhashed with salt:  mypassword210211  hashed with salt:  cbc0a790b2f28fc72ca43eb749028b9f    Then if I check my password today:   unhashed with salt:  mypassword30012012  hashed with salt:  e4af7ca7e263750a15be642d903c9ac9    They're completely different, so how does the script know that they are the same? Do I have to store the salt used on the specified password in the database so it knows what to use next time?  I'm rather confused and its highly likely that I am not understanding the whole hashing process properly. I've done my research, but whether I have done correctly or not I don't know.
40789
Can anyone recommend a straightforward way/tool to convert hex to base64?  I'm using Linux and OS X.
34586
I needed some simple string encryption, so I wrote the following code (with a great deal of "inspiration" from ):      // create and initialize a crypto algorithm     private static SymmetricAlgorithm getAlgorithm(string password) {         SymmetricAlgorithm algorithm = Rijndael.Create();         Rfc2898DeriveBytes rdb = new Rfc2898DeriveBytes(             password, new byte[] {             0x53,0x6f,0x64,0x69,0x75,0x6d,0x20,             // salty goodness             0x43,0x68,0x6c,0x6f,0x72,0x69,0x64,0x65         }         );         algorithm.Padding = PaddingMode.ISO10126;         algorithm.Key = rdb.GetBytes(32);         algorithm.IV = rdb.GetBytes(16);         return algorithm;     }      /*       * encryptString      * provides simple encryption of a string, with a given password      */     public static string encryptString(string clearText, string password) {         SymmetricAlgorithm algorithm = getAlgorithm(password);         byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(clearText);         MemoryStream ms = new MemoryStream();         CryptoStream cs = new CryptoStream(ms, algorithm.CreateEncryptor(), CryptoStreamMode.Write);         cs.Write(clearBytes, 0, clearBytes.Length);         cs.Close();         return Convert.ToBase64String(ms.ToArray());     }      /*      * decryptString      * provides simple decryption of a string, with a given password      */     public static string decryptString(string cipherText, string password) {         SymmetricAlgorithm algorithm = getAlgorithm(password);         byte[] cipherBytes = Convert.FromBase64String(cipherText);         MemoryStream ms = new MemoryStream();         CryptoStream cs = new CryptoStream(ms, algorithm.CreateDecryptor(), CryptoStreamMode.Write);         cs.Write(cipherBytes, 0, cipherBytes.Length);         cs.Close();                     return System.Text.Encoding.Unicode.GetString(ms.ToArray());     }   The code appears to work fine, except that when decrypting data with an incorrect key, I get a CryptographicException - "Padding is invalid and cannot be removed" - on the cs.Close() line in decryptString.   example code:      string password1 = "password";     string password2 = "letmein";     string startClearText = "The quick brown fox jumps over the lazy dog";     string cipherText = encryptString(startClearText, password1);     string endClearText = decryptString(cipherText, password2);     // exception thrown   My question is, is this to be expected? I would have thought that decrypting with the wrong password would just result in nonsense output, rather than an exception.
48753
I've come up with this little routine for doing encryption using the SHA-2 (in this case SHA-256) hash function. As such it is a block cipher with a 256 bit (32 byte) block size and an arbitrary key length. It's easy to see that you could replace the hash function and get an entirely new type of algorithm.  I want to know if there are any problems, especially flaws, in this construction, and whether algorithms of this type have been studied.  Initialization with key:  $$ S_0 = H(k) $$  Encryption for plaintext blocks $P_1, \dots P_n$:  $$ S_i = H(S_{i-1})$$   $$ C_i = P_i \oplus S_i $$  Decryption for ciphertext blocks $C_1 \dots C_n$:  $$ S_i = H(S_{i-1})$$   $$ P_i = C_i \oplus S_i $$  Here is some sample C source code using SSL:  #include &lt;openssl/sha.h&gt;  struct sha_crypt_state {     unsigned char digest[SHA256_DIGEST_LENGTH]; };  void sha_crypt_set_key( sha_crypt_state *state, unsigned char *key, int key_length ) {     SHA256( key, key_length, state-&gt;digest ); }  void sha_crypt( sha_crypt_state *state, unsigned char *block ) {     sha_crypt_state temp;     SHA256( state-&gt;digest, sizeof(state-&gt;digest), temp.digest );     memcpy( state-&gt;digest, temp.digest, sizeof(temp.digest) );      for ( int i = 0; i &lt; sizeof(state-&gt;digest); ++i ) {         block[i] ^= state-&gt;digest[i];     } }  void sha_crypt_test() {     const char *key = "secret";      // prepare a test block     char block[SHA256_DIGEST_LENGTH];     memset( block, 0, sizeof(block) );     strcpy( block, "Hello, testing encryption!" );      // test encrypt     sha_crypt_state state;     set_key( &amp;state, (unsigned char *)key, strlen(key) );     sha_crypt( &amp;state, (unsigned char *)block );      // test decrypt     set_key( &amp;state, (unsigned char *)key, strlen(key) );     sha_crypt( &amp;state, (unsigned char *)block ); }
114816
I have an API Integration which expects a HMAC-SHA256 signature. Example:  message = 'testmessage' secret key = '123456789' signature: 9cba4d1d75689509208a97b1ca42f786a630a891e2410bfb11a84feb7a4807ad   How can I generate the same signature in Apex? I tried the generateMac function from the Crypto class but it gives a different value than the one expected. Below is the code:  Blob blobSignature = Crypto.generateMac('HmacSHA256', Blob.valueOf('testmessage'), Blob.valueOf('123456789')); System.debug(EncodingUtil.base64Encode(blobSignature));   Output: nLpNHXVolQkgipexykL3hqYwqJHiQQv7EahP63pIB60=  What I am doing incorrectly here?
18427
I have an image that is Base64 encoded. What is the best way to decode that in Java? Hopefully using only the libraries included with Sun Java 6.
90748
Let's imagine a cipher that works like the following:   Plaintext is encoded to Base64. The characters in the encoded plaintext are substituted with a randomly shuffled character set(A-z, 0-9, -, _, =).  The shuffled alphabet is, in essence, the key.   Not particularly complex or even secure.  But...  What if I wanted to do frequency analysis?  For example, "RUNFORYOURLIFE" when encoded in Base64 is:  UlVORk9SWU9VUkxJRkU=  When the character set is shuffled, the final cryptext can look something like this:  xv24DYG9qxG2xYg6DYxf  The key being:   yhAc5bTOWeYvBXCpVuoMJLdg8P1jHN3ZIsi67SrK4E_D9-x2qRQmnlkwUaFt0G=zf  Which is a shuffled version of:  abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_=  Let's also assume that the character set in subsequent messages is in the same order(ie the key is re-used).  Since the bytes are basically split up resulting in different character units that may or may not correspond, is frequency analysis still feasible?  Does encoding plaintext this way before encryption add any form of security?  My question mostly pertains to longer messages, as my example may be too short for any sort of real analysis.
40564
I'm retrieving a gzipped web page via curl, but when I output the retrieved content to the browser I just get the raw gzipped data. How can I decode the data in PHP?  One method I found was to write the content to a tmp file and then ...  $f = gzopen($filename,"r"); $content = gzread($filename,250000); gzclose($f);   .... but man, there's got to be a better way.  Edit: This isn't a file, but a gzipped html page returned by a web server.
104837
Any decent hash algorithm will produce basically "random like" values for any given input including the empty input.  For example MD5 produces d41d8cd98f00b204e9800998ecf8427e on an empty input.  I wonder, however, why the MD5 algorithm wasn't defined to have a final step where the output is XORed with d41d8cd98f00b204e9800998ecf8427e. This should not affect the cryptographic strength of the hash algorithm, and it would have the convenient property that a hash of all zeros represented a zero input.  Would it simply just because adding that step would slow the hash down a bit?
47668
I am tasked with writing an authentication component for an open source JAVA app.  We have an in-house authentication widget that uses https.  I have some example php code that accesses the widget which uses cURL to handle the transfer.    My question is whether or not there is a port of cURL to JAVA, or better yet, what base package will get me close enough to handle the task?   Update:  This is in a nutshell, the code I would like to replicate in JAVA:  $cp = curl_init(); $my_url = "https://" . AUTH_SERVER . "/auth/authenticate.asp?pt1=$uname&amp;pt2=$pass&amp;pt4=full"; curl_setopt($cp, CURLOPT_URL, $my_url); curl_setopt($cp, CURLOPT_RETURNTRANSFER, 1); $result = curl_exec($cp); curl_close($cp);   , I think you're on the right track, I think I'm going to end up using HttpsURLConnection and then picking out what I need from the response.
28212
There are many examples of MD5 collisions (some of them can be found here ). But as far as I know two inputs should have the same length to have the same MD5 (or same hash in general). Is it correct? Is there any proof of that?  Or otherwise examples of inputs of different lengths with the same MD5?
71900
In languages like Java and C#, strings are immutable and it can be computationally expensive to build a string one character at a time.  In said languages, there are library classes to reduce this cost such as C# System.Text.StringBuilder and Java java.lang.StringBuilder.  Does php (4 or 5; I'm interested in both) share this limitation?  If so, are there similar solutions to the problem available?
33014
I have the string which that encoded in .  How do I decode this in php?  Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Vestibulum felis = pede, vestibulum et, ullamcorper in, ultrices eget, metus. Suspendisse in n= ulla. Sed justo. Donec dapibus auctor neque. Pellentesque faucibus ante nec=  metus. Vivamus feugiat, velit rhoncus semper suscipit, libero augue venena= tis leo, nec ornare nulla elit eget diam. Nullam sollicitudin.