Solved

Simple Encryption

Posted on 2013-05-14
10
243 Views
Last Modified: 2013-05-24
NOTE: Any web language example would be fine.

This question is solely for my own understanding. I realize it is not practical in use.

I want to code a simple encryption technique. It works like this:

KeyPhrase1:  PasZcode
KeyPhrase2:  Secret

Correct Password is: john
Entered Password: john

To obtain it...

1 Take position of character [j] in alphabet , which would be 10.
2. Get Letter in KeyPhrase1 at that position (10th). I suppose we would use MOD here, 10%len(keyphrase1) ? which would be 2, correct?
3. That would give us "a"
4. Take "a" position in alphabet ( 1 ) and Get Letter in KeyPhrase2 ( S )

So the first encrypted letter of john, would be S.

My Question is, how would I do this in code? How would I check to see if THEY ENTERED the correct password?

I have a feeling one of you EXPERTS could probably do this in one line of code ..

// Can someone help me with this complex statement, please?

Open in new window


My goal is to write code which the correct password is NOT in the source code. Again, I realize this is not practical  but I will put to use elsewhere once I fully understand how this works. THANKS AGAIN!
0
Comment
Question by:edvinson
  • 4
  • 2
  • 2
  • +2
10 Comments
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
I've never seen anything quite like that.  Scrambled alphabets are usually considered too easy to break, and so most programmers choose some other kind of obfuscation (usually a salted MD5 or an encryption).  I'll try to show you some of the teaching examples that might make sense for your needs.
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Here's a basic way to scramble letters.
http://php.net/manual/en/function.str-rot13.php

Here's an example of encryption.
<?php // RAY_encrypt_decrypt.php
error_reporting(E_ALL);

// MAN PAGE: http://php.net/manual/en/ref.mcrypt.php

class Encryption
{
    protected $key;
    protected $eot;
    protected $ivs;
    protected $iv;

    public function __construct($key='quay', $eot='___EOT')
    {
        // SET KEY, DELIMITER, INITIALIZATION VECTOR - MUST BE KNOWN TO BOTH PARTS OF THE ALGORITHM
        $this->key = $key;
        $this->eot = $eot;
        $this->ivs = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
        $this->iv  = mcrypt_create_iv($this->ivs);
    }

    public function encrypt($text)
    {
        // APPEND END OF TEXT DELIMITER
        $text .= $this->eot;

        // ENCRYPT THE DATA
        $data = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $this->key, $text, MCRYPT_MODE_ECB, $this->iv);

        // MAKE IT base64() STRING SAFE FOR STORAGE AND TRANSMISSION
        return base64_encode($data);
    }

    public function decrypt($text)
    {
        // DECODE THE DATA INTO THE BINARY ENCRYPTED STRING
        $text = base64_decode($text);

        // DECRYPT THE STRING
        $data = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $this->key, $text, MCRYPT_MODE_ECB, $this->iv);

        // REMOVE END OF TEXT DELIMITER
        $data = explode($this->eot, $data);
        return $data[0];
    }
}

// INSTANTIATE THE CLASS
$c = new Encryption();

// INITIALIZE VARS FOR LATER USE IN THE HTML FORM
$encoded = '';
$decoded = '';

// IF ANYTHING WAS POSTED SHOW THE DATA
if (!empty($_POST["clearstring"]))
{
    $encoded = $c->encrypt($_POST["clearstring"]);
    echo "<br/>{$_POST["clearstring"]} YIELDS ENCODED ";
    var_dump($encoded);
}

if (!empty($_POST["cryptstring"]))
{
    $decoded = $c->decrypt($_POST["cryptstring"]);
    echo "<br/>{$_POST["cryptstring"]} YIELDS DECODED ";
    var_dump($decoded);
}

$form = <<<FORM
<form method="post">
<input name="clearstring" value="$decoded" />
<input type="submit" value="ENCRYPT" />
<br/>
<input name="cryptstring" value="$encoded" />
<input type="submit" value="DECRYPT" />
</form>
FORM;

echo $form;

Open in new window

0
 
LVL 6

Expert Comment

by:BurundiLapp
Comment Utility
Writing your basic encryption algorithm is one way to go but the ones in PHP already are much more efficient.

For isntance one way to this is to use MD5 salted hashes, that means taking the password that the user enters, adding a known addition to it (your salt) and then creating an MD5 hash of that new phrase.

So if I enter the password 'password123' and the salt you are using is 'Dresden' then the resulting concatanated string would 'password123Dresden'.

Convert that to an MD5 hash (  $hashedpass = md5($saltedpass); ) and then store that in your passwords database/file.

Whenever the user logs into the site then the password they enter has the salt added to it, it's made into a MD5 hash and compared to the MD5 hash you have stored in your passwords database/file.  if the hashes match then they can login, at no point are you keeping their unencrypted password and because the hash is salted it can't be matched against the unsalted hash tables that are out on the internet if your passwords database/file gets compromised.
0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
Comment Utility
And here's a little more structured and obscure way to scramble letters.  None of these ways will ultimately keep a secret, but they will at least force a casual onlooker to exert some effort to discern the meaning.  None of these will work well with UTF-8, but if you're just using western (ascii) characters and not multi-byte characters you should be OK.
http://www.laprbass.com/RAY_scramble_word.php

<?php // RAY_scramble_word.php
error_reporting(E_ALL);
echo '<pre>';

Class Scramble
{
    protected $clear = '$%-., 0123456789@ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';
    protected $scram = 'fjAEokIOzU2q13_h5w794p@6s8B.gPdFVmDTcSZe%r,lGKuCyJxHiQLt-RMa$NvW Ynb0X';

    public function __construct($num = 0)
    {
        if ($num <  1) $num = 0;
        if ($num >= strlen($this->scram)) $num = 0;
        if ($num)
        {
            $scr_1 = substr($this->scram, 0, $num);
            $scr_2 = substr($this->scram, $num);
            $this->scram = $scr_2 . $scr_1;
        }

        $this->endex = array_combine(str_split($this->clear), str_split($this->scram));
        $this->dedex = array_flip($this->endex);
    }

    public function encode($word)
    {
        return strtr($word, $this->clear, $this->scram);
    }

    public function decode($word)
    {
        return strtr($word, $this->scram, $this->clear);
    }

}

// USE CASE WITH RANDOM SCRAMBLE CODE
$obj = new Scramble(rand(8,18));
$old = 'Supercalifragilisticexpialidocious! is a word from Mary Poppins';
$scr = $obj->encode($old);
$new = $obj->decode($scr);

// SHOW THE WORK PRODUCT
var_dump($old, $scr, $new);

Open in new window

HTH, ~Ray
0
 
LVL 82

Expert Comment

by:Dave Baldwin
Comment Utility
If you are submitting the data over the web, the best encryption you can get is to make it a secure connection by getting an SSL/TLS certificate for your website.  That provides end-to-end encryption of the data path from the browser to the web server.

Passwords that are used with logins on a PHP/MySQL site are not usually stored in the clear.  They are typically stared in the database as an MD5 hash of the original password.  The submitted password is hashed and compared to the hash in the database.  Though supposedly MD5 can be broken with a supercomputer, no one is going to try that unless you are storing state secrets.
0
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 33

Expert Comment

by:Slick812
Comment Utility
Greetings   edvinson, , You ask about encryption, and you give a "process" for what you might consider to be a way to do encryption, However, the "process" you give can NOT ever return the same "plaintext" as john, after you put this "john" through your process using the alphabetic position as 10.
The reason is, for all encryption processes you must use the EXACT same process in reverse, that you use  to encrypt the plaintext. If you use the MOD for getting the KeyPhrase letter, it can not be reversed as
10%len(keyphrase1),
would not be reversible, because you have lost the most significant information, that is the number 10, you must know this 10 after decryption, in order to ever find the original "j" letter.
 I am not sure what you are asking about in your question, I have done much in digital encryption, if you want to know about digital encryption, you might look at some web tutorials,
Maybe if you can give more information about what result you need in code, or what your question has for the "start" as "one plain-text and two Key-phrases" and what your code output result needs to be, then I can give some ways to do it. But I do not see any way to Code what you have given.
0
 
LVL 33

Expert Comment

by:Slick812
Comment Utility
This is the best I could do with your encrypt concept, using the alphabetical position of the plain-text, and a Modulus of the keys. Unlike your Idea, if you use  alphabetical position, then you are limited to one character set, small letters in this case "john", No Capitals allowed (or punctuation).

// make an aray to get alphabet number position from letter
$subArry = array('a'=>0,'b'=>1,'c'=>2,'d'=>3,'e'=>4,'f'=>5,'g'=>6,'h'=>7,'i'=>8,'j'=>9,'k'=>10,'l'=>11,
	'm'=>12,'n'=>13,'o'=>14,'p'=>15,'q'=>16,'r'=>17,'s'=>18,'t'=>19,'u'=>20,'v'=>21,'w'=>22,'x'=>23,'y'=>24,'z'=>25);
$decArry =array_flip($subArry); // reverse the array for number to letter
$pass = 'john';
$key1 = 'paszcode';
$key2 = 'secret';

$encArry = array();
for ($i=0;$i< strlen($pass);++$i)
	$encArry[] = $subArry[$pass{$i}];// get number values in an array
$total1 = 0;
for ($i=0;$i< strlen($key1);++$i)
	$total1 += $subArry[$key1{$i}]; // add all of KEY ONE together
$total1 %= 26;
$total2 = 0;
for ($i=0;$i< strlen($key2);++$i)
	$total2 += $subArry[$key2{$i}]; // add all of KEY TWO together
$total2 %= 26;
for ($i=0;$i< count($encArry);++$i)
	$encArry[$i] = ($encArry[$i]+$total1)%26;/  MOD the addition to 26
for ($i=0;$i< count($encArry);++$i)
	$encArry[$i] = ($encArry[$i]+$total2)%26;
$encrypt = '';
for ($i=0;$i< count($encArry);++$i)
	$encrypt .= $decArry[$encArry[$i]]; // change the numbers to letters
echo 'Encrypt is=',$encrypt,'<br />';


// DECRYPT BELOW, do exact reverse of encrypt
$key1 = 'paszcode';
$key2 = 'secret';
$encArry = array();
for ($i=0;$i< strlen($encrypt);++$i)
	$encArry[] = $subArry[$encrypt{$i}];
$total1 = 0;
for ($i=0;$i< strlen($key1);++$i)
	$total1 += $subArry[$key1{$i}];
$total1 %= 26;
$total2 = 0;
for ($i=0;$i< strlen($key2);++$i)
	$total2 += $subArry[$key2{$i}];
$total2 %= 26;
for ($i=0;$i< count($encArry);++$i)
	$encArry[$i] = (($encArry[$i]+26)-$total2)%26;
for ($i=0;$i< count($encArry);++$i)
	$encArry[$i] = (($encArry[$i]+26)-$total1)%26;
$decrypt = '';
for ($i=0;$i< count($encArry);++$i)
	$decrypt .= $decArry[$encArry[$i]];
echo 'Decrypt is=',$decrypt,'<br />';

Open in new window

But this is limited and not difficult to figure out, but can stump most programmers!
0
 
LVL 82

Expert Comment

by:hielo
Comment Utility
>>My Question is, how would I do this in code?
See code at the end.

>>How would I check to see if THEY ENTERED the correct password? My goal is to write code which the correct password is NOT in the source code.
The "plain" password would NOT be in the source code, BUT the encrypted password would need to be saved somewhere so that you have something to compare it against.

Thus, if you create a "New Account" form where I am required to establish a username and password, what you will need to do is encrypt the password -- thus, if my password was 'john', based on the algorithm you provided, the encrypted password will be 'Srec' -- and store it (typically onto a database).

Then, once my account is active, I would then go to your login form, where I need to type my credentials.  On your processing script/page, you will need to take the password that I typed ('john') and encrypt it (you should get 'Srec').  Now that you have the encrypted password, you need to query the DB using the encrypted password:
$username= $_POST['username'];
$password= enc($_POST['password'],'PasZcode','Secret');

$rs=mysql_query("SELECT FirstName,LastName,Email FROM Account WHERE username='$username' AND password='$password' ") or die(mysql_error());

/* Assuming that username is 'john@company.com', the above essentially executes:
SELECT FirstName,LastName,Email FROM Account WHERE username='john@company.com' and password='Srec'
if there is a record that matches the above criteria, you will get a non-empty result set in $rs.  For this to work, you have to make sure that in your DB table the username field is UNIQUE.
*/

Open in new window


NOTE: the above snippet is just for illustration purposes.  Going forward you should be using "mysqli_..." instead of "mysql_...".

function enc($password,$KeyPhrase1,$KeyPhrase2)
{
	//provide list of characters that may be part of the password
	$A=Array ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
			, 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
			, '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
			);

	//change $A to the format Array('a'=>0,'b'=>1,'c'=>2,...) for faster lookups
	$A=array_flip($A);

	/*
	KeyPhrase1:  PasZcode
	KeyPhrase2:  Secret

	1 Take position of character [j] in alphabet , which would be 10.
	2. Get Letter in KeyPhrase1 at that position (10th). I suppose we would use MOD here, 10%len(keyphrase1) ? which would be 2, correct?
	3. That would give us "a"
	4. Take "a" position in alphabet ( 1 ) and Get Letter in KeyPhrase2 ( 1 % strlen($KeyPhrase2) => S )
	
	By manual computation, the encryption for 'john' should be 'Srec'
	*/
	$output='';
	for($i=0, $limit=strlen($password); $i < $limit; ++$i)
	{
		//Step 1
		// $password[$i] will give you a letter in $password.  Use that letter to retrieve
		// corresponding number in $A
		$letter=$password[$i];
		$position=$A[$letter];
	
		//Step 2
		$position=$position % strlen($KeyPhrase1);
		
		//Step 3
		$letter=$KeyPhrase1[$position];
	
		//Step 4
		$position=$A[$letter] % strlen($KeyPhrase2);
		$output.=$KeyPhrase2[$position];
	}
return $output;
}

enc('john','PasZcode','Secret');

Open in new window

0
 
LVL 82

Expert Comment

by:Dave Baldwin
Comment Utility
What @hielo shows above is the method that is usually used with MD5 or SHA1 which are much more secure than any substitution code.
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Thanks for the points, ~Ray
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Having worked on larger scale sites, we found out that you are bound to look at more scalable solutions to integrating widgets, code snippets or complete applications and mesh them into functional sites, in any given composition. To share some of…
JavaScript can be used in a browser to change parts of a webpage dynamically. It begins with the following pattern: If condition W is true, do thing X to target Y after event Z. Below are some tips and tricks to help you get started with JavaScript …
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

7 Experts available now in Live!

Get 1:1 Help Now