class material

10
 20/11/2014 Hashi ng and Publ i c Key Encr ypti on | Gl ynRob https://glynrob.com/php/hashing-and-public-key-encr ypti on/ 1/10  GlynRob All about code and tech Home About Me Learning + Reading PHP, PYTHON Hashing and Public Ke y Encryption by GlynRob • October 19, 2013 • 7 Comments All code examples available at: https://github.com/glynrob/encryption Hashing Hashing is an important part of the storing the passwords of your users in your database. You do not need to know or be able to look up the password a user used. Instead you want to be able to validate that the password is correct then let them continue on your website/app. So how do you do this? In all programming languages there are hashing functions available to you that do this. This is not encryption, as hashing is only be made one way, it can not be reversed to get the original password. If your database was ever hacked and copied by a third party (it has happened to very big companies so could easily happen to you too) then the hash password you stored will not show the passwords of your users. Many users use the same password on all websites which means that attacker can now try other websites with the same credentials to gain access. Salt

Upload: ioio92

Post on 07-Oct-2015

7 views

Category:

Documents


0 download

DESCRIPTION

Lol

TRANSCRIPT

  • 20/11/2014 Hashing and Public Key Encryption | GlynRob

    https://glynrob.com/php/hashing-and-public-key-encryption/ 1/10

    GlynRobAll about code and tech

    Home About Me Learning + Reading

    PHP, PYTHON

    Hashing and Public KeyEncryptionby GlynRob October 19, 2013 7 Comments

    All code examples available at: https://github.com/glynrob/encryption

    HashingHashing is an important part of the storing the passwords of your users in your database.You do not need to know or be able to look up the password a user used. Instead you wantto be able to validate that the password is correct then let them continue on yourwebsite/app.So how do you do this?In all programming languages there are hashing functions available to you that do this.This is not encryption, as hashing is only be made one way, it can not be reversed to get theoriginal password.If your database was ever hacked and copied by a third party (it has happened to very bigcompanies so could easily happen to you too) then the hash password you stored will notshow the passwords of your users.Many users use the same password on all websites which means that attacker can now tryother websites with the same credentials to gain access.

    Salt

  • 20/11/2014 Hashing and Public Key Encryption | GlynRob

    https://glynrob.com/php/hashing-and-public-key-encryption/ 2/10

    view raw

    Salt is a term used when hashing data which simply means adding some data.So if your password was monkey123, when you hash this password you actually hashmonkey123SALTVALThe salt value should be unqiue to the user also so you DO NOT USE THE SAME SALT valuefor all users.If the same salt was used then it would be easier for the attacker to create its own rainbowtable (try all password variations) to find the original unhashed password.Therefore you need to now save 2 items of data for this user.

    Hashed passwordSalt value

    This salt value should be random and not just the unix time stamp of the server when it wascreated. My examples use methods like openssl_random_pseudo_bytes but other optionslike mcrypt_create_iv are just as suitable.The more random and longer the string is, the better.

    Hashing functions

    There are many different hashing functions available so I choose 3 to sample.

    MD5 Now very weak so do not useSHA1 Stronger but still not suitableSHA512 Strong and recommended

    What you aim to do is choose a function that takes awhile to generate the output.You want to do this to avoid possible rainbow tables, the longer it takes to get 1 result thelonger it will take an attacker for each possible password.You could hash the value 100 times to make the generation time longer but keep an eye onyour server if many people are logging in at the same time.

    PHP Example:

    12345678

    $md5 = md5($password.$salt);echo "MD5 = $md5"; $sha1 = sha1($password.$salt);echo "SHA1 = $sha1"; $sha512 = hash('sha512', $password.$salt);echo "SHA512 = $sha512";

    gistfile1.php hosted with by GitHub

    Python Example:

    123

    md5 = hashlib.md5()md5.update(password+saltstring)print 'MD5 = '+md5.hexdigest()

    ioniMettre en vidence

  • 20/11/2014 Hashing and Public Key Encryption | GlynRob

    https://glynrob.com/php/hashing-and-public-key-encryption/ 3/10

    view raw

    456789

    sha1string = hashlib.sha1(password + saltstring)print 'SHA1 = '+sha1string.hexdigest() sha1string = hashlib.sha512(password + saltstring)print 'SHA512 = '+sha1string.hexdigest()

    gistfile1.py hosted with by GitHub

    You save the salt value for that user and the hashed value when they create their account.Next time they try to login you generate a hash using the same method but with the savedsalt value and if the hash matches, then the password was correct.

    Public Key EncryptionPublic Key Encryption is used to encrypt data from one point and allow it to be decrypted inanother using different keys.This is used for saving sensitive users data in a database, or passing information from oneserver to another.This means a provider can have his own private key which he never shares with anyone, butprovides multiple public keys to other which allows them to encrypt the data to be sent tohim. Only the provider with the private key can decrypt this data.

    There are other encryption methods available, but my examples use openSSLhttps://github.com/glynrob/encryption

    DO NOT USE MY PUBLIC KEY except for testing. This private key is public so anyone candecrypt any data you send using this.To generate your own private and public keys you can use:

    Linux/MAC:# private keyopenssl genrsa -out mykey.pem 2048# public keyopenssl rsa -in mykey.pem -pubout -out mykey.pub

    Windows:Puttygen or one of the other software providershttps://www.racf.bnl.gov/docs/authentication/ssh/sshkeygenwin

    If you run the examples I provided for PHP and Python you should see the following output.

  • 20/11/2014 Hashing and Public Key Encryption | GlynRob

    https://glynrob.com/php/hashing-and-public-key-encryption/ 4/10

    view raw

    view raw

    From this example you see a string encrypted which can then be sent anywhere, then it isdecrypted back with the private key.

    Example function PHP:

    1234567891011121314151617

    function public_encrypt($plaintext){ $fp=fopen("./mykey.pub","r"); $pub_key=fread($fp,8192); fclose($fp); openssl_get_publickey($pub_key); openssl_public_encrypt($plaintext,$crypttext, $pub_key ); return(base64_encode($crypttext)); } function private_decrypt($encryptedext){ $fp=fopen("./mykey.pem","r"); $priv_key=fread($fp,8192); fclose($fp); $private_key = openssl_get_privatekey($priv_key); openssl_private_decrypt(base64_decode($encryptedext), $decrypted, $private_key); return $decrypted; }

    gistfile1.php hosted with by GitHub

    Example function Python:

    123456789

    rsa = RSA.load_pub_key("mykey.pub")ctxt = rsa.public_encrypt(secretstring, RSA.pkcs1_padding)encryptedText = ctxt.encode('base64')print 'Encrypted Text = '+encryptedText priv = RSA.load_key("mykey.pem")decodeEncryptedText = encryptedText.decode('base64')decryptedText = priv.private_decrypt(decodeEncryptedText, RSA.pkcs1_padding)print 'Decrypted Text = '+decryptedText

    gistfile1.py hosted with by GitHub

    It really is as easy as that to encrypt and decrypt data.

    Just ensure that the private key is only available at the locations where it is required.

  • 20/11/2014 Hashing and Public Key Encryption | GlynRob

    https://glynrob.com/php/hashing-and-public-key-encryption/ 5/10

    Tags: Hashing md5 PHP private key public key Python sha1 sha512

    Minify Javascript Git Cheatsheet

    7 comments for Hashing and Public Key Encryption

    Share this:

    PBMay 10, 2014 at 1:57 pm

    So I have two questions:

    1. How do I get the private & public keys into a plain text format (maybebase64) and then send it to the different parties (via email) and then turnthose plain text back into keys so they can encrypt / decrypt? So like inyour examples, instead of loading key from file, they would enter the plaintext (copy&paste) version & let the program (php) convert to keys for theen/decrypt.

    2. Because of converting to plain text, is it possible to have a small privatekey bit size? Say something like 40bits? Php complains & doesnt allow meto have anything below 300 some odd bits. I am not so much worriedabout the strength of the cypher more worried about the manageabilityof they keys.

    For example , I would like to have a web from end where a user can entertheir private key to decrypt a message from either the system or anotheruser. Or have all the messages encrypted with one public key & the privatekey would be split up between 2 or 3 people. The messages cant bedecrypted until all the holders of the chunks of the private have enteredtheir chunk into the web page. Therefore the chunks should be small 9-12 bytes or so.

    the site is running php & on shared hosting plan so no access to cmdline.

    any thoughts?

  • 20/11/2014 Hashing and Public Key Encryption | GlynRob

    https://glynrob.com/php/hashing-and-public-key-encryption/ 6/10

    GlynRobMay 10, 2014 at 8:53 pm

    Hi PB,

    For what you are trying to do I would use something like Crypto.js.I have covered this http://glynrob.com/javascript/client-side-hashing-and-encryption/

    You can view the contents of server side public and private keys in thecommand line, but you should never email a private key as this is not asecure way to share information.

    Hope this helps

    NavinderAugust 7, 2014 at 8:41 pm

    Hi, I tried copying and pasting your code to my encrpt.php file and calledthe function aspublic_encrypt(plain text here);But it is always showing a blank page. I tried copying and pasting theentire public key from file but still a blank output.I am using a MAC.

    Can you please suggest what I may be doing wrong? Thank you.

    MIkeSeptember 29, 2014 at 8:05 pm

    Hello, I have learn a lot from your articles.But have question using a public and private keys.on the server this is great, encrypting on the client side with a public key isalso straight forward. What happens if you need to decrypt on the clientsside with the private key like in your example? Is there a technique forthis? Or do you just need to make sure the private key is secured.

  • 20/11/2014 Hashing and Public Key Encryption | GlynRob

    https://glynrob.com/php/hashing-and-public-key-encryption/ 7/10

    GlynRobOctober 6, 2014 at 6:57 pm

    Mike: To encrypt and decrypt on the client side read this other blog postI did.http://glynrob.com/javascript/client-side-hashing-and-encryption/

    Gavin HansonNovember 11, 2014 at 1:56 am

    Hello GlynThis is a very helpful article however it does not cover how to go aboutencrypting long strings.

    Taken from php.net discussion about openssl_public_encrypt().

    When you encrypt something using an RSA key (whether public orprivate), the encrypted value must be smaller than the key (due to themaths used to do the actual encryption). So if you have a 1024-bit key, intheory you could encrypt any 1023-bit value (or a 1024-bit value smallerthan the key) with that key.

    Is there is best practise work around to this?

    GlynRobNovember 14, 2014 at 1:46 pm

    One way would be to break your content into chunks and encrypt themseparately.http://phpseclib.sourceforge.net/ does this but you could easilyimplement a similar solution yourself.

    Another option is to use openssl_seal() and openssl_open(). openssl_sealgenerates a random string, encrypts it with RSA and then encrypts thedata youre actually trying to encrypt with RC4 using the random stringas the key.

  • 20/11/2014 Hashing and Public Key Encryption | GlynRob

    https://glynrob.com/php/hashing-and-public-key-encryption/ 8/10

    Leave a ReplyYour email address will not be published. Required fields are marked *

    Name *

    Email *

    Website

    Comment

    Post Comment

    Notify me of follow-up comments by email.

    Notify me of new posts by email.

    Search

    Find Me

    Categories

  • 20/11/2014 Hashing and Public Key Encryption | GlynRob

    https://glynrob.com/php/hashing-and-public-key-encryption/ 9/10

    Apps (1)CSS (5)Database (4)General (9)Hardware (3)Javascript (13)PHP (6)Python (2)Security (6)Versioning (2)

    Ads

    Tweets

    ArchivesNovember 2014March 2014November 2013October 2013July 2013March 2013February 2013January 2013December 2012November 2012October 2012September 2012July 2012June 2012May 2012March 2012January 2012

    Tags

    addons andriod app AutoSave AWS CodeIgniter css CVS downloading file sharing firefox git Hardware

    @markrussinovich Already done :) But on Amazon.co.uk

    Last week from Glyn Roberts's Twitter

  • 20/11/2014 Hashing and Public Key Encryption | GlynRob

    https://glynrob.com/php/hashing-and-public-key-encryption/ 10/10

    Hashing html html5 interviews java Javascript jobs jQuery lego LESS CSS linuxlocalStorag localStorage memcache MongoDB NFC node.js NoSQL online phone PHP Python

    Raspberry Pi Redis security SVN Symfony templating Versioning virus W3C Web Storage

    Copyright 2014 GlynRob. All Rights Reserved.Sitemap