January 7, 2008

Encrypt-Decrypt String (2)

Filed under: Blogramming

Yang ini dari temanku, Dandi. Memakai Class bawaan .Net yang menggunakan metode Rinjdael. Memakai bahasa C#.

using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using System.Collections;

public class AES_Cryptography
{
    public const int KEYSIZE_128 = 128;
    public const int KEYSIZE_192 = 192;
    public const int KEYSIZE_256 = 256;

    public const string HASH_MD5 = "MD5";
    public const string HASH_SHA1 = "SHA1";

    private string getRandomPassword()
    {
        string strOut = "";
        Random rnd = new Random();
        for (int i = 0; i < 8; i++)
            strOut = strOut + Convert.ToChar(rnd.Next(0, 254)).ToString();
        MD5 md5 = new MD5CryptoServiceProvider();
        byte[] strTemp = md5.ComputeHash(Encoding.UTF8.GetBytes(strOut));
        string sOut = "";
        foreach (byte b in strTemp)
        {
            sOut += String.Format("{0:x2}", b);
        }
        sOut = sOut.Substring(8, 16);
        return sOut;
    }

    private string getRandomSalt()
    {
        string strOut = "";
        Random rnd = new Random();
        for (int i = 0; i < 8; i++)
            strOut = strOut + Convert.ToChar(rnd.Next(0, 254)).ToString();
        MD5 md5 = new MD5CryptoServiceProvider();
        byte[] strTemp = md5.ComputeHash(Encoding.UTF8.GetBytes(strOut));
        string sOut = "";
        foreach (byte b in strTemp)
        {
            sOut += String.Format("{0:x2}", b);
        }
        sOut = sOut.Substring(8, 16);
        return sOut;
    }

    private string getRandomInitVector()
    {
        string strOut = "";
        Random rnd = new Random();
        for (int i = 0; i < 8; i++)
            strOut = strOut + Convert.ToChar(rnd.Next(0, 254)).ToString();
        MD5 md5 = new MD5CryptoServiceProvider();
        byte[] strTemp = md5.ComputeHash(Encoding.UTF8.GetBytes(strOut));
        string sOut = "";
        foreach (byte b in strTemp)
        {
            sOut += String.Format("{0:x2}", b);
        }
        sOut = sOut.Substring(8, 16);
        return sOut;
    }

    public string encryptString(string clearText)
    {
        try
        {
            string cipherText = "";
            string strPass = getRandomPassword();
            string strSalt = getRandomSalt();
            string strIV = getRandomInitVector();

            string cipherOut;
            MemoryStream mStream = new MemoryStream();
            Rijndael rCrypt = Rijndael.Create();

            PasswordDeriveBytes password = new PasswordDeriveBytes(strPass, Encoding.ASCII.GetBytes(strSalt), AES_Cryptography.HASH_MD5, 9);

            rCrypt.Key = password.GetBytes(AES_Cryptography.KEYSIZE_256 / 8 ) ;
            rCrypt.IV = Encoding.ASCII.GetBytes(strIV);

            CryptoStream cStream = new CryptoStream(mStream, rCrypt.CreateEncryptor(rCrypt.Key, rCrypt.IV), CryptoStreamMode.Write);
            cStream.Write(Encoding.UTF8.GetBytes(clearText), 0, Encoding.UTF8.GetBytes(clearText).Length);
            cStream.FlushFinalBlock();

            cipherText = Convert.ToBase64String(mStream.ToArray());

            cStream.Close();
            mStream.Close();

            cipherText = strPass.Substring( 0 , 8 ) + strIV + cipherText + strSalt + strPass.Substring(8, 8 ) ;

            cipherOut = cipherText;
            return cipherOut;
        }
        catch (Exception exp)
        {
            throw new Exception(exp.Message, exp);
        }
    }

    public string decryptString(string cipherText)
    {
        try
        {
            MemoryStream mStream = new MemoryStream();
            Rijndael rCrypt = Rijndael.Create();
            string textOut;

            string strOut = "";
            string strPass = cipherText.Substring(0, 8 ) + cipherText.Substring(cipherText.Length - 8, 8 ) ;
            string strSaltValue = cipherText.Substring(cipherText.Length - (8 + 16), 16);
            string strIV = cipherText.Substring(8, 16);

            cipherText = cipherText.Substring(24, cipherText.Length - 16 - 16 - 16);

            PasswordDeriveBytes password = new PasswordDeriveBytes(strPass, Encoding.ASCII.GetBytes(strSaltValue), AES_Cryptography.HASH_MD5, 9);

            rCrypt.Key = password.GetBytes(AES_Cryptography.KEYSIZE_256 / 8 ) ;
            rCrypt.IV = Encoding.ASCII.GetBytes(strIV);

            CryptoStream cStream = new CryptoStream(mStream, rCrypt.CreateDecryptor(rCrypt.Key, rCrypt.IV), CryptoStreamMode.Write);
            cStream.Write(Convert.FromBase64String(cipherText), 0, Convert.FromBase64String(cipherText).Length);
            cStream.FlushFinalBlock();

            strOut = Encoding.UTF8.GetString(mStream.ToArray());

            cStream.Close();
            mStream.Close();

            textOut = strOut;
            return textOut;
        }
        catch (Exception exp)
        {
            throw new Exception(exp.Message, exp);
        }
    }

    public string encryptString(string clearText, string passKey)
    {
        try
        {
            string cipherText = "";
            string strPass = passKey;
            string strSalt = getRandomSalt();
            string strIV = getRandomInitVector();

            string cipherOut;
            MemoryStream mStream = new MemoryStream();
            Rijndael rCrypt = Rijndael.Create();

            PasswordDeriveBytes password = new PasswordDeriveBytes(strPass, Encoding.ASCII.GetBytes(strSalt), AES_Cryptography.HASH_MD5, 9);

            rCrypt.Key = password.GetBytes(AES_Cryptography.KEYSIZE_256 / 8 ) ;
            rCrypt.IV = Encoding.ASCII.GetBytes(strIV);

            CryptoStream cStream = new CryptoStream(mStream, rCrypt.CreateEncryptor(rCrypt.Key, rCrypt.IV), CryptoStreamMode.Write);
            cStream.Write(Encoding.UTF8.GetBytes(clearText), 0, Encoding.UTF8.GetBytes(clearText).Length);
            cStream.FlushFinalBlock();

            cipherText = Convert.ToBase64String(mStream.ToArray());

            cStream.Close();
            mStream.Close();

            cipherText = strIV + cipherText + strSalt;

            cipherOut = cipherText;
            return cipherOut;
        }
        catch (Exception exp)
        {
            throw new Exception(exp.Message, exp);
        }
    }

    public string decryptString(string cipherText, string passKey)
    {
        try
        {
            MemoryStream mStream = new MemoryStream();
            Rijndael rCrypt = Rijndael.Create();
            string textOut;

            string strOut = "";
            string strPass = passKey;
            string strSaltValue = cipherText.Substring(cipherText.Length - (16), 16);
            string strIV = cipherText.Substring(0, 16);

            cipherText = cipherText.Substring(16, cipherText.Length - 16 - 16);

            PasswordDeriveBytes password = new PasswordDeriveBytes(strPass, Encoding.ASCII.GetBytes(strSaltValue), AES_Cryptography.HASH_MD5, 9);

            rCrypt.Key = password.GetBytes(AES_Cryptography.KEYSIZE_256 / 8 ) ;
            rCrypt.IV = Encoding.ASCII.GetBytes(strIV);

            CryptoStream cStream = new CryptoStream(mStream, rCrypt.CreateDecryptor(rCrypt.Key, rCrypt.IV), CryptoStreamMode.Write);
            cStream.Write(Convert.FromBase64String(cipherText), 0, Convert.FromBase64String(cipherText).Length);
            cStream.FlushFinalBlock();

            strOut = Encoding.UTF8.GetString(mStream.ToArray());

            cStream.Close();
            mStream.Close();

            textOut = strOut;
            return textOut;
        }
        catch (Exception exp)
        {
            throw new Exception(exp.Message, exp);
        }
    }
}

Encrypt-Decrypt String (1)

Filed under: Blogramming

Class berikut ini berfungsi untuk meng-encrypt-decrypt string. Misalnya untuk keperluan meng-enkripsi password, dll. Masih menggunakan vb.Net 2005. Menggunakan class yang menggunakan metode TripleDes.

Imports System.IO
Imports System.Security.Cryptography
Imports System.Text

Public Class zSecurity
    Dim password As String = "ZE161207"
    Dim salt() As Byte = {&H0, &H1, &H2, &H3, &H4, &H5, &H6, &HF1, &HF0, &HEE, &H21, &H22, &H45}

    Public Function EncryptString(ByVal str As String) As String
        Dim k1 As New Rfc2898DeriveBytes(password, salt, 1000)
        Dim encAlg As TripleDES = TripleDES.Create()
        encAlg.Key = k1.GetBytes(16)

        Dim encryptionStream As New MemoryStream()
        Dim encrypt As New CryptoStream(encryptionStream, encAlg.CreateEncryptor(), CryptoStreamMode.Write)
        Dim utfD1 As Byte() = New System.Text.UTF8Encoding(False).GetBytes(str)
        encrypt.Write(utfD1, 0, utfD1.Length)
        encrypt.FlushFinalBlock()
        encrypt.Close()
        Dim edata1 As Byte() = encryptionStream.ToArray()
        k1.Reset()

        Return Convert.ToBase64String(edata1) & Convert.ToBase64String(encAlg.IV) ‘Encoding.ASCII.GetString(encAlg.IV)
    End Function

    Public Function DecryptString(ByVal str As String) As String
        Dim k2 As New Rfc2898DeriveBytes(password, salt)

        Dim strIV As String = str.Substring(str.Length - 12, 12)
        str = str.Substring(0, str.Length - 12)

        Dim decAlg As TripleDES = TripleDES.Create()
        decAlg.Key = k2.GetBytes(16)
        decAlg.IV = Convert.FromBase64String(strIV)
        Dim decryptionStreamBacking As New MemoryStream()
        Dim decrypt As New CryptoStream(decryptionStreamBacking, decAlg.CreateDecryptor(), CryptoStreamMode.Write)
        decrypt.Write(Convert.FromBase64String(str), 0, Convert.FromBase64String(str).Length)
        decrypt.Flush()
        decrypt.Close()
        k2.Reset()
        Return New UTF8Encoding(False).GetString(decryptionStreamBacking.ToArray())
    End Function
End Class

January 4, 2008

Mapping Drive

Filed under: Blogramming

Class di bawah ini untuk melakukan mapping drive ke komputer lain. Dapet dari suatu sumber, terus dimodifikasi. Menggunakan vb.Net, versi 2005.

Public Class Mapping_Drive
    Public Declare Function WNetAddConnection2 Lib "mpr.dll" Alias "WNetAddConnection2A" (ByRef lpNetResource As NETRESOURCE, ByVal lpPassword As String, ByVal lpUserName As String, ByVal dwFlags As Integer) As Integer

    Public Declare Function WNetCancelConnection2 Lib "mpr" Alias "WNetCancelConnection2A" _
(ByVal lpName As String, ByVal dwFlags As Integer, ByVal fForce As Integer) As Integer

    <Runtime.InteropServices.StructLayout(Runtime.InteropServices.LayoutKind.Sequential)> _
    Public Structure NETRESOURCE
        Public dwScope As Integer
        Public dwType As Integer
        Public dwDisplayType As Integer
        Public dwUsage As Integer
        Public lpLocalName As String
        Public lpRemoteName As String
        Public lpComment As String
        Public lpProvider As String
    End Structure

    Public Const ForceDisconnect As Integer = 1
    Public Const RESOURCETYPE_DISK As Long = &H1

    Public Function MapDrive(ByVal DriveLetter As String, ByVal UNCPath As String, ByVal strUsername As String, ByVal strPassword As String) As Boolean

        Dim nr As NETRESOURCE

        nr = New NETRESOURCE
        nr.lpRemoteName = UNCPath
        nr.lpLocalName = DriveLetter & ":"
        nr.dwType = RESOURCETYPE_DISK

        Dim result As Integer
        result = WNetAddConnection2(nr, strPassword, strUsername, 0)

        If result = 0 Then
            Return True
        Else
            Return False
        End If
    End Function

    Public Function MapDrive(ByVal DriveLetter As String, ByVal UNCPath As String) As Boolean

        Dim nr As NETRESOURCE
        Dim strUsername As String
        Dim strPassword As String

        nr = New NETRESOURCE
        nr.lpRemoteName = UNCPath
        nr.lpLocalName = DriveLetter & ":"
        strUsername = Nothing ‘(add parameters to pass this if necessary)
        strPassword = Nothing ‘(add parameters to pass this if necessary)
        nr.dwType = RESOURCETYPE_DISK

        Dim result As Integer
        result = WNetAddConnection2(nr, strPassword, strUsername, 0)

        If result = 0 Then
            Return True
        Else
            Return False
        End If
    End Function

    Public Function UnMapDrive(ByVal DriveLetter As String) As Boolean
        Dim rc As Integer
        rc = WNetCancelConnection2(DriveLetter & ":", 0, ForceDisconnect)

        If rc = 0 Then
            Return True
        Else
            Return False
        End If

    End Function
End Class