This is example code for AES Encrypted String:
Public Function AES_Encrypt(ByVal input As String, ByVal pass As String) As String
Dim AES As New System.Security.Cryptography.RijndaelManaged
Dim Hash_AES As New System.Security.Cryptography.MD5CryptoServiceProvider
Dim encrypted As String = ""
Try
Dim hash(31) As Byte
Dim temp As Byte() = Hash_AES.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(pass))
Array.Copy(temp, 0, hash, 0, 16)
Array.Copy(temp, 0, hash, 15, 16)
AES.Key = hash
AES.Mode = Security.Cryptography.CipherMode.ECB
Dim DESEncrypter As System.Security.Cryptography.ICryptoTransform = AES.CreateEncryptor
Dim Buffer As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(input)
encrypted = Convert.ToBase64String(DESEncrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
Return encrypted
Catch ex As Exception
End Try
End Function
Public Function AES_Decrypt(ByVal input As String, ByVal pass As String) As String
Dim AES As New System.Security.Cryptography.RijndaelManaged
Dim Hash_AES As New System.Security.Cryptography.MD5CryptoServiceProvider
Dim decrypted As String = ""
Try
Dim hash(31) As Byte
Dim temp As Byte() = Hash_AES.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(pass))
Array.Copy(temp, 0, hash, 0, 16)
Array.Copy(temp, 0, hash, 15, 16)
AES.Key = hash
AES.Mode = Security.Cryptography.CipherMode.ECB
Dim DESDecrypter As System.Security.Cryptography.ICryptoTransform = AES.CreateDecryptor
Dim Buffer As Byte() = Convert.FromBase64String(input)
decrypted = System.Text.ASCIIEncoding.ASCII.GetString(DESDecrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
Return decrypted
Catch ex As Exception
End Try
End Function
Saturday, March 29, 2014
Friday, March 28, 2014
How to Catching the close button event click
This is an example code for knowing when we click on close button:
Example 1:
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
MessageBox.Show("Closing Form")
End Sub
Example 2:
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
If boolCloseByButton Then
'Closed by a different button
Else
'Closed by the x on the form
End If
End Sub
Example 3:
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
'You could put a Select Case statement here and take action for all
'different types of closing conditions.
If e.CloseReason = System.Windows.Forms.CloseReason.UserClosing Then
'Closed by the x on the form or Alt-F4
Else
'Closed for some other reason
End If
End Sub
Wednesday, March 26, 2014
hex to string conversion
This is an example of hex to string:
Function HexToString(ByVal hex As String) As String Dim text As New System.Text.StringBuilder(hex.Length \ 2) For i As Integer = 0 To hex.Length - 2 Step 2 text.Append(Chr(Convert.ToByte(hex.Substring(i, 2), 16))) Next Return text.ToString End Function
How to use:
Console.WriteLine(HexToString("73696D306E"))
Tuesday, March 25, 2014
Getting JSTL to run within Tomcat and Eclipse
It's very simple to include jstl in your projects, what I do is:
- Download jstl-1.2.jar (JSP 2.1 containers only i.e. Tomcat 6, otherwise jstl-1.1.jar) fromhttp://repo1.maven.org/maven2/javax/servlet/jstl/1.2/
or
the interfaces (javax.servlet.jsp.jstl-api-1.2.1.jar) from http://search.maven.org/#browse|707331597and the actual implementing classes (javax.servlet.jsp.jstl-1.2.2.jar) fromhttp://search.maven.org/#browse%7C-1002239589. - Copy to your project's WEB-INF/lib directory
- Include the following tags in yours jsp's:
- <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
- <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
- <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
- <%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>
As for eclipse I need to know if your using any framework plugin, I use MyEclipse and it does it automatically for me.
Friday, March 21, 2014
VB.NET Split
The Split function separates Strings. It receives a string or character delimiter. It parses and separates the source string by separating the parts that come between the delimiter. It is used often in VB.NET programs.
Notes:Input string = "Dot Net Perls".
Delimiter = space.
Output array = "Dot" "Net" "Perls".
Delimiter = space.
Output array = "Dot" "Net" "Perls".
Example
To start, we split a VB.NET String based on a space character. We allocate a New Char array as well as a String array to store the words. Finally we loop over the Strings and display them to the Console.
Char ArrayString ArrayProgram that uses Split on String: VB.NET
Module Module1
Sub Main()
' We want to split this input string
Dim s As String = "there is a cat"
' Split string based on spaces
Dim words As String() = s.Split(New Char() {" "c})
' Use For Each loop over words and display them
Dim word As String
For Each word In words
Console.WriteLine(word)
Next
End Sub
End Module
Output
there
is
a
cat
File path parts
Continuing on, we Split a file system path into separate parts using Visual Basic .NET. We use a New Char array with one string, "\""c. We then loop through and display the results.
Program that splits file path: VB.NET
Module Module1
Sub Main()
' The file system path we need to split
Dim s As String = "C:\Users\Sam\Documents\Perls\Main"
' Split the string on the backslash character
Dim parts As String() = s.Split(New Char() {"\"c})
' Loop through result strings with For Each
Dim part As String
For Each part In parts
Console.WriteLine(part)
Next
End Sub
End Module
Output
C:
Users
Sam
Documents
Perls
Main
Regex.Split words
Often you need to extract the words from a String or sentence. The code here needs to handle punctuation and non-word characters differently than the String Split method. Here we use Regex.Split to parse the words.
Program that splits words: VB.NET
Imports System.Text.RegularExpressions
Module Module1
Sub Main()
' Declare iteration variable
Dim s As String
' Loop through words in string
Dim arr As String() = SplitWords("That is a cute cat, man!")
' Display each word. Note that punctuation is handled correctly.
For Each s In arr
Console.WriteLine(s)
Next
Console.ReadLine()
End Sub
''' <summary>
''' Split the words in string on non-word characters.
''' This means commas and periods are handled correctly.
''' </summary>
Private Function SplitWords(ByVal s As String) As String()
'
' Call Regex.Split function from the imported namespace.
' Return the result array.
'
Return Regex.Split(s, "\W+")
End Function
End Module
Output
That
is
a
cute
cat
man
In the Main subroutine you can see that two variables are declared. The second variable is a String array that receives the results from the Private Function next. This is the SplitWords Function.
Regex. The Function shown in the example calls the Regex.Split method, which can be accessed with dot notation, with no instance necessary. The second argument to the method is a regular expression pattern.
Regex.Split
Regex pattern. The pattern "\W+" is used, and this means "one or more non-word characters". This pattern will match punctuation and spaces. Therefore all those characters will be used as delimiters.
Note:Regex Functions tend to be slower. They can handle much more complex patterns than the String Split Function.
And:It is best to use the fastest and simplest Function that handles your problem.
File lines
Next, we see one way to Split each line in a file using File.ReadAllLines and Split. We have a comma-separated-values CSV file, and want to print out each value and its row number. It first reads in the file with ReadAllLines.
Then:This function puts each line in the file into an array element. The example Splits on ","c. We show the output of the program.
File HandlingInput file used
frontal,parietal,occipital,temporal
pulmonary artery,aorta,left ventricle
Program that splits lines: VB.NET
Imports System.IO
Module Module1
Sub Main()
Dim i As Integer = 0
' Loop through each line in array returned by ReadAllLines
Dim line As String
For Each line In File.ReadAllLines("example.txt")
' Split line on comma
Dim parts As String() = line.Split(New Char() {","c})
' Loop over each string received
Dim part As String
For Each part In parts
' Display to Console
Console.WriteLine("{0}:{1}", i, part)
Next
i += 1
Next
End Sub
End Module
Output
0:frontal
0:parietal
0:occipital
0:temporal
1:pulmonary artery
1:aorta
1:left ventricle
Summary
We saw some ways to Split your String in VB.NET. Split returns a String array that you can use in a For Each loop. We used Split on different characters and strings. Then we called Regex.Split in a more complex pattern example.
Convert a String to Stream
Why have you converted binary (image) data to a string? This makes no sense... unless you are using base-64?
Anyway, to reverse what you have done, you could try using new MemoryStream(Encoding.UTF8.GetBytes(text))?
This will create a new MemoryStream primed with the string (via UTF8). Personally, I doubt it will work - you are going to run into a lot of encoding issues treating raw binary as UTF8 data... I expect either the read or write (or both) to throw an exception.
(edit)
I should add that to work with base-64, simply get the data as a byte[], then call Convert.ToBase64String(...); and to get back the array, just use Convert.FromBase64String(...).
Re your edit, this is precisely what I tried to warn about above... in .NET, a string is not just a byte[], so you can't simply fill it with binary image data. A lot of the data simply won't make sense to the encoding, so might be quietly dropped (or an exception thrown).
To handle raw binary (such as images) as strings, you need to use base-64 encoding; this adds size, however. Note that WebClient might make this simpler, as it exposes byte[] functionality directly:
using(WebClient wc = new WebClient()) {
byte[] raw = wc.DownloadData("http://www.google.com/images/nav_logo.png")
//...
}
Anyway, using a standard Stream approach, here's how to encode and decode the base-64:
// ENCODE
// where "s" is our original stream
string base64;
// first I need the data as a byte[]; I'll use
// MemoryStream, as a convenience; if you already
// have the byte[] you can skip this
using (MemoryStream ms = new MemoryStream())
{
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = s.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, bytesRead);
}
base64 = Convert.ToBase64String(ms.GetBuffer(), 0, (int) ms.Length);
}
// DECODE
byte[] raw = Convert.FromBase64String(base64);
using (MemoryStream decoded = new MemoryStream(raw))
{
// "decoded" now primed with the binary
}
Anyway, to reverse what you have done, you could try using new MemoryStream(Encoding.UTF8.GetBytes(text))?
This will create a new MemoryStream primed with the string (via UTF8). Personally, I doubt it will work - you are going to run into a lot of encoding issues treating raw binary as UTF8 data... I expect either the read or write (or both) to throw an exception.
(edit)
I should add that to work with base-64, simply get the data as a byte[], then call Convert.ToBase64String(...); and to get back the array, just use Convert.FromBase64String(...).
Re your edit, this is precisely what I tried to warn about above... in .NET, a string is not just a byte[], so you can't simply fill it with binary image data. A lot of the data simply won't make sense to the encoding, so might be quietly dropped (or an exception thrown).
To handle raw binary (such as images) as strings, you need to use base-64 encoding; this adds size, however. Note that WebClient might make this simpler, as it exposes byte[] functionality directly:
using(WebClient wc = new WebClient()) {
byte[] raw = wc.DownloadData("http://www.google.com/images/nav_logo.png")
//...
}
Anyway, using a standard Stream approach, here's how to encode and decode the base-64:
// ENCODE
// where "s" is our original stream
string base64;
// first I need the data as a byte[]; I'll use
// MemoryStream, as a convenience; if you already
// have the byte[] you can skip this
using (MemoryStream ms = new MemoryStream())
{
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = s.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, bytesRead);
}
base64 = Convert.ToBase64String(ms.GetBuffer(), 0, (int) ms.Length);
}
// DECODE
byte[] raw = Convert.FromBase64String(base64);
using (MemoryStream decoded = new MemoryStream(raw))
{
// "decoded" now primed with the binary
}
Thursday, March 20, 2014
How to encrypt and decrypt data in Java?
Symmetric Encryption
Symmetric encryption uses the same key for both encryption and decryption. In Java, use an instance of javax.crypto.Cipher. Example:
import java.security.*;
import javax.crypto.*;
Cipher aes = Cipher.getInstance("AES/ECB/PKCS5Padding");
aes.init(Cipher.ENCRYPT_MODE, key);
byte[] ciphertext = aes.doFinal("my cleartext".getBytes());
aes.init(Cipher.DECRYPT_MODE, key);
String cleartext = new String(aes.doFinal(ciphertext));
The key for the cipher should be an instance of javax.crypto.spec.SecretKeySpec. AES in particular requires its key to be created with exactly 128 bits (16 bytes).
A simple way to get the required number of bytes is to take a variable length passphrase and hash it with a java.security.MessageDigest such as SHA1. For example:
import java.security.*;
import javax.crypto.spec.*;
String passphrase = "correct horse battery staple";
MessageDigest digest = MessageDigest.getInstance("SHA");
digest.update(passphrase.getBytes());
SecretKeySpec key = new SecretKeySpec(digest.digest(), 0, 16, "AES");
A better way to create a key is with a SecretKeyFactory using a salt:
byte[] salt = "choose a better salt".getBytes();
int iterations = 10000;
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
SecretKey tmp = factory.generateSecret(new PBEKeySpec(passphrase.toCharArray(), salt, iterations, 128));
SecretKeySpec key = new SecretKeySpec(tmp.getEncoded(), "AES");
PBKDF2 is an algorithm specially designed for generating keys from passwords that is considered more secure than a simple SHA1 hash. The salt ensures your encryption won't match another encryption using the same key and cleartext and helps prevent dictionary attacks. The iterations value is an adjustable parameter. Higher values use more computing power, making brute force attacks more difficult.
Asymmetric Encryption
Asymmetric encryption, also called public key encryption, uses a key pair. One part of the key is used to encrypt and the other to decrypt. This allows you to make the encryption key public, allowing anyone to generate messages only you, the holder of the private decryption key, can read. Alternatively, you can encrypt with the private key, useful for digital signatures.
As with symmetric encryption, use an instance of javax.crypto.Cipher:
import java.security.*;
Cipher rsa = Cipher.getInstance("RSA/ECB/PKCS1Padding");
rsa.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] ciphertext = rsa.doFinal("my cleartext".getBytes());
rsa.init(Cipher.DECRYPT_MODE, privateKey);
String cleartext = new String(rsa.doFinal(ciphertext));
In this case the keys will be instances of java.security.PublicKey and java.security.PrivateKey. To generate a new pair:
import java.security.*;
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
Public and private keys can also be transformed into byte arrays for storage and transmission:
import java.security.*;
import java.security.spec.*;
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
byte[] publicKeyBytes = publicKey.getEncoded();
KeySpec keySpec = new X509EncodedKeySpec(publicKeyBytes);
PublicKey keyFromBytes = keyFactory.generatePublic(keySpec);
Symmetric encryption uses the same key for both encryption and decryption. In Java, use an instance of javax.crypto.Cipher. Example:
import java.security.*;
import javax.crypto.*;
Cipher aes = Cipher.getInstance("AES/ECB/PKCS5Padding");
aes.init(Cipher.ENCRYPT_MODE, key);
byte[] ciphertext = aes.doFinal("my cleartext".getBytes());
aes.init(Cipher.DECRYPT_MODE, key);
String cleartext = new String(aes.doFinal(ciphertext));
The key for the cipher should be an instance of javax.crypto.spec.SecretKeySpec. AES in particular requires its key to be created with exactly 128 bits (16 bytes).
A simple way to get the required number of bytes is to take a variable length passphrase and hash it with a java.security.MessageDigest such as SHA1. For example:
import java.security.*;
import javax.crypto.spec.*;
String passphrase = "correct horse battery staple";
MessageDigest digest = MessageDigest.getInstance("SHA");
digest.update(passphrase.getBytes());
SecretKeySpec key = new SecretKeySpec(digest.digest(), 0, 16, "AES");
A better way to create a key is with a SecretKeyFactory using a salt:
byte[] salt = "choose a better salt".getBytes();
int iterations = 10000;
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
SecretKey tmp = factory.generateSecret(new PBEKeySpec(passphrase.toCharArray(), salt, iterations, 128));
SecretKeySpec key = new SecretKeySpec(tmp.getEncoded(), "AES");
PBKDF2 is an algorithm specially designed for generating keys from passwords that is considered more secure than a simple SHA1 hash. The salt ensures your encryption won't match another encryption using the same key and cleartext and helps prevent dictionary attacks. The iterations value is an adjustable parameter. Higher values use more computing power, making brute force attacks more difficult.
Asymmetric Encryption
Asymmetric encryption, also called public key encryption, uses a key pair. One part of the key is used to encrypt and the other to decrypt. This allows you to make the encryption key public, allowing anyone to generate messages only you, the holder of the private decryption key, can read. Alternatively, you can encrypt with the private key, useful for digital signatures.
As with symmetric encryption, use an instance of javax.crypto.Cipher:
import java.security.*;
Cipher rsa = Cipher.getInstance("RSA/ECB/PKCS1Padding");
rsa.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] ciphertext = rsa.doFinal("my cleartext".getBytes());
rsa.init(Cipher.DECRYPT_MODE, privateKey);
String cleartext = new String(rsa.doFinal(ciphertext));
In this case the keys will be instances of java.security.PublicKey and java.security.PrivateKey. To generate a new pair:
import java.security.*;
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
Public and private keys can also be transformed into byte arrays for storage and transmission:
import java.security.*;
import java.security.spec.*;
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
byte[] publicKeyBytes = publicKey.getEncoded();
KeySpec keySpec = new X509EncodedKeySpec(publicKeyBytes);
PublicKey keyFromBytes = keyFactory.generatePublic(keySpec);
Saturday, March 15, 2014
Timer in VB.NET
Public Class Form1
Private _elapseTimerRunning As Boolean = False
Private _elapseStartTime As DateTime
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Timer1.Interval = 1000
Timer1.Enabled = True
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
txtTime.Text = Now.ToString("h:mm:ss tt")
If _elapseTimerRunning = True Then
Dim elapsedtime = DateTime.Now.Subtract(_elapseStartTime)
txtElapsed.Text = String.Format("{0}hr : {1}min : {2}sec", elapsedtime.Hours, elapsedtime.Minutes, elapsedtime.Seconds)
End If
End Sub
Private Sub btnStart_Click(sender As Object, e As EventArgs) Handles btnStart.Click
_elapseStartTime = DateTime.Now
_elapseTimerRunning = True
End Sub
Private Sub btnStop_Click(sender As Object, e As EventArgs) Handles btnStop.Click
_elapseTimerRunning = False
End Sub
End Class
Timer to count down in VB.Net 2010
This is an example of using VB.NET to count down time:
Public Class frmSinglePlayer
Private TargetDT As DateTime
Private CountDownFrom As TimeSpan = TimeSpan.FromMinutes(3)
Private Sub frmSinglePlayer_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
tmrCountdown.Interval = 500
TargetDT = DateTime.Now.Add(CountDownFrom)
tmrCountdown.Start()
End Sub
Private Sub tmrCountdown_Tick(sender As Object, e As System.EventArgs) Handles tmrCountdown.Tick
Dim ts As TimeSpan = TargetDT.Subtract(DateTime.Now)
If ts.TotalMilliseconds > 0 Then
lblTime.Text = ts.ToString("mm\:ss")
Else
lblTime.Text = "00:00"
tmrCountdown.Stop()
MessageBox.Show("Done")
End If
End Sub
End Class
Public Class frmSinglePlayer
Private TargetDT As DateTime
Private CountDownFrom As TimeSpan = TimeSpan.FromMinutes(3)
Private Sub frmSinglePlayer_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
tmrCountdown.Interval = 500
TargetDT = DateTime.Now.Add(CountDownFrom)
tmrCountdown.Start()
End Sub
Private Sub tmrCountdown_Tick(sender As Object, e As System.EventArgs) Handles tmrCountdown.Tick
Dim ts As TimeSpan = TargetDT.Subtract(DateTime.Now)
If ts.TotalMilliseconds > 0 Then
lblTime.Text = ts.ToString("mm\:ss")
Else
lblTime.Text = "00:00"
tmrCountdown.Stop()
MessageBox.Show("Done")
End If
End Sub
End Class
Thursday, March 13, 2014
Insert SQL command with Datetime in MS-Access
Date & Time input in access use #, since access can't do auto conversion from char/text into date or time in SQL Query (or access call it query), and you better use international standard for inputting date time which was YYYY-MM-DD HH:NN:SS (4-digit year, 2-digit month, 2-digit day, 2-digit hour, 2-digit minute, 2-digit second)
so for 4/21/2009 2:25:53 PM use #2009-04-21 14:25:53#
or if it still fail, you can use #'2009-04-21 14:25:53'#
Edit: Above might be working if you enable ANSI 92 or using ADO/OLEDB as database interface, thanks David for pointing out
I suggest you use YYYY-MM-DD HH:NN:SS format and try it with single quotes (') before use # like i said above
Wednesday, March 12, 2014
Best way to use PHP to encrypt and decrypt passwords?
You should not encrypt passwords, instead you should hash them using an algorithm like bcrypt. Still, here is how you would encrypt/decrypt:
$key = 'password to (en/de)crypt';
$string = ' string to be encrypted '; // note the spaces
To Encrypt:
$iv = mcrypt_create_iv(
mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC),
MCRYPT_DEV_URANDOM
);
$encrypted = base64_encode(
$iv .
mcrypt_encrypt(
MCRYPT_RIJNDAEL_256,
hash('sha256', $key, true),
$string,
MCRYPT_MODE_CBC,
$iv
)
);
To Decrypt:
$data = base64_decode($encrypted);
$iv = substr($data, 0, mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC));
$decrypted = rtrim(
mcrypt_decrypt(
MCRYPT_RIJNDAEL_256,
hash('sha256', $key, true),
substr($data, mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC)),
MCRYPT_MODE_CBC,
$iv
),
"\0"
);
echo 'Encrypted:' . "\n";
var_dump($encrypted); // "ey7zu5zBqJB0rGtIn5UB1xG03efyCp+KSNR4/GAv14w="
echo "\n";
echo 'Decrypted:' . "\n";
var_dump($decrypted); // " string to be encrypted "
Found this class recently, it works like a dream!
class Encryption {
var $skey = "yourSecretKey"; // you can change it
public function safe_b64encode($string) {
$data = base64_encode($string);
$data = str_replace(array('+','/','='),array('-','_',''),$data);
return $data;
}
public function safe_b64decode($string) {
$data = str_replace(array('-','_'),array('+','/'),$string);
$mod4 = strlen($data) % 4;
if ($mod4) {
$data .= substr('====', $mod4);
}
return base64_decode($data);
}
public function encode($value){
if(!$value){return false;}
$text = $value;
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $this->skey, $text, MCRYPT_MODE_ECB, $iv);
return trim($this->safe_b64encode($crypttext));
}
public function decode($value){
if(!$value){return false;}
$crypttext = $this->safe_b64decode($value);
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$decrypttext = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $this->skey, $crypttext, MCRYPT_MODE_ECB, $iv);
return trim($decrypttext);
}
}
And to call it:
$str = "My secret String";
$converter = new Encryption;
$encoded = $converter->encode($str );
$decoded = $converter->decode($encoded);
echo "$encoded<p>$decoded";
Subscribe to:
Comments (Atom)

