Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts

Friday, November 14, 2008

PBE - Eveet yine hiç anlamadığım konuda iki satır yazdım hoşuma gitti

PBE password based encryption demek. bu ne demek şifreli şifreleme metodu. yani "abc" diye bi stringimiz var biz bunu şifrelemek istiyoruz ve kendimiza ait bi şifreyle bunu yapmak istiyoruz. mesele "123" e göre şifrelencek. neyse daha önceki yazımda jasypt ve javasından bahsetmiştim. decrytpinide yaptım koyim bi yerde dursun dedim hoşuma gitti şukadarcık kod cirlop gibide çalışıo.


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

namespace StandardPBEStringEncryptor
{
public static class CryptoLib
{
public static string EncryptId(string ID)
{
string result = "";
ID = "abc" + ID + "xyz";
byte[] salt = new byte[8];

RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(salt);

System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
PKCSKeyGenerator kp = new PKCSKeyGenerator();
ICryptoTransform crypt = kp.Generate(
"kunteper",
salt,
1000,
1);

byte[] sonuc = crypt.TransformFinalBlock(encoding.GetBytes(ID), 0, encoding.GetBytes(ID).Length);

foreach (byte item in salt)
{
result += item.ToString("X2");
}
foreach (byte item in sonuc)
{
result += item.ToString("X2");
}
return result;
}
public static byte[] fromHexadecimal(String message)
{
if (message == null)
{
return null;
}
if ((message.Length % 2) != 0)
{
throw new Exception("bu iş olmaz mesaj bozuk");
}
try
{
byte[] result = new byte[message.Length / 2];
for (int i = 0; i < message.Length; i = i + 2)
{
int first = Convert.ToInt32("" + message[i], 16);
int second = Convert.ToInt32("" + message[i + 1], 16);
result[i / 2] = (byte)(0x0 + ((first & 0xff) << 4) + (second & 0xff));
}
return result;
}
catch (Exception e)
{
throw e;
}
}
public static string DecryptId(string ID)
{
byte[] pnlContent = fromHexadecimal(ID);
byte[] salt = new byte[8];
byte[] encryptedMessageKernel = new byte[24];
Array.Copy(pnlContent, salt, 8);
Array.Copy(pnlContent, 8, encryptedMessageKernel, 0, 24);

PKCSKeyGenerator kp = new PKCSKeyGenerator();
ICryptoTransform crypt = kp.Generate(
"kunteper"
, salt
, 1000
, 1);

byte[] sonuc = kp.Decryptor.TransformFinalBlock(encryptedMessageKernel, 0, encryptedMessageKernel.Length);
return Encoding.ASCII.GetString(sonuc).Replace("abc","").Replace("xyz","");
}
}

public class PKCSKeyGenerator
{
byte[] key = new byte[8], iv = new byte[8];
DESCryptoServiceProvider des = new DESCryptoServiceProvider();

public byte[] Key { get { return key; } }
public byte[] IV { get { return iv; } }
public ICryptoTransform Encryptor { get { return des.CreateEncryptor(key, iv); } }
public ICryptoTransform Decryptor { get { return des.CreateDecryptor(key, iv); } }

public PKCSKeyGenerator() { }
public PKCSKeyGenerator(String keystring, byte[] salt, int md5iterations, int segments)
{
Generate(keystring, salt, md5iterations, segments);
}

public ICryptoTransform Generate(String keystring, byte[] salt, int md5iterations, int segments)
{
int HASHLENGTH = 16;
byte[] keymaterial = new byte[HASHLENGTH * segments];
byte[] psbytes;
psbytes = Encoding.UTF8.GetBytes(keystring);

byte[] data00 = new byte[psbytes.Length + salt.Length];
Array.Copy(psbytes, data00, psbytes.Length);
Array.Copy(salt, 0, data00, psbytes.Length, salt.Length);

MD5 md5 = new MD5CryptoServiceProvider();
byte[] result = null;
byte[] hashtarget = new byte[HASHLENGTH + data00.Length];
for (int j = 0; j < segments; j++)
{
if (j == 0) result = data00;
else
{
Array.Copy(result, hashtarget, result.Length);
Array.Copy(data00, 0, hashtarget, result.Length, data00.Length);
result = hashtarget;
}

for (int i = 0; i < md5iterations; i++)
result = md5.ComputeHash(result);

Array.Copy(result, 0, keymaterial, j * HASHLENGTH, result.Length);
}

Array.Copy(keymaterial, 0, key, 0, 8);
Array.Copy(keymaterial, 8, iv, 0, 8);

return Encryptor;
}
}
}



biliyorum kırılır belkide kıranınız vardır bana fark etmez :) ben sevdim bu olayı.

sanırım bende çok okumadım olay bu pkcs#5

Monday, November 10, 2008

Jasypt StandardPBEStringEncryptor C#

bi şekilde encrypt etmem gereken bi string problemim var normalde hiç uğraşmadığım kriptoloji hikayelerini kurcalamaya başlıyorum. olayım şu jasypt de bulunan StandardPBEStringEncryptor şifreleyicisiyle şifrelenmiş gibi bi string oluşturmak sanırım cipher de diolar yani şifreli veri. neyse en son bir örnek buldum ama çıkan sonuç nedense javadan çıkanla aynı boyda değil.

kurcalıom kurcalıom zaten anlamadığım bok örnek ve döküman az. en sonunda sikerim örneğini diyip. girdim java koduna başladım debug etmeye. meğersem salt+encryptedMessage yapmak gerekiomuş. bulduğum örnekse sadece encrypted ı geri gönderio sonradan kavradım olayı 8byte lık salt la 24 bytelık mesajı birleştirip yolluosunki karşı tarafda onu deşifre edebilsin. jasypt den de testimi yaptım dalga doğru çalışıo ferahladım. böle şeyleri çözmeside eğlenceli oluormuş.

Monday, October 20, 2008

Lucene.net ve asp.net

lucene apache nin altında arama işlerinde kullanılan epey oturmuş bir proje. fakat java ile yazılmış bende bugün asp.net ile nasıl olurda kullanabilirim diye bakındım. ve basit bir asp.net örneği bulamadım. neyse diğer örneklerden kendime bişekil çalışan bişey çıkardım bu sefer godaddy shared hosting security exceptionları vermeye başladı ulan dedim noluyor. meğer lucene.net in te aşşalarında çağrılan iki satır kod ortamı karıştırırmış allah google amcamdan razı olsun birisi evvelden çözmüş o problemide ortadan kaldırdım.

sonra dedimki madem ben bulamadım başkasıda bulamayabilir bunu bi article edelim biyerlere koyalım. çok teferruatlı olmadı sonuçda teferruat olucak bişeyde yok en basit bi şekilde index nasıl create edilir nasıl arama yapılır ve sonuçlar gösterilir diye merak edenleriniz varsa bir aspx dosyasında işi bitirdim mis oldu.

Download luceneExample.zip - 196.7 KB

Sunday, October 12, 2008

apostrof urlencode olmadı

normalde html de bi link oluştururken apostrofu encode etmeniz gerekmez ama ben <a href='adres'>isim</a> şeklinde link oluşturuyordum tabi bu adresin içinde apostrof olma ihtimali hiç gelmezdi aklıma bi bakdım link bozuluyor. .net için HttpUtility.UrlEncode() fonksiyonunu kullanim dedim. link değişmedi meğersem bu konular kıl olabilirmiş. neyse çözüme gelelim hemen

linkStringi.Replace("'","%27");

bu şekilde replace edince konu çözüldü.

hadi hayırlı tıraşlar.

Tuesday, February 19, 2008

Vista is a total disaster or what

some part of my program could not work on vista. it says "no authorization". this program developed under .net 2 simple program shows some web pages from internet stands in system tray. thats the program in this post.

and it uses webbrowser component of .net. I know microsoft build up a new most secure system for their customers. but it works in XP. there must be some option about vista situation. now I am thinking C++ will be more easy but I am not sure. anyway time will show.

NotifyIcon and double click problem

in .net 2 if you want to show your application in system tray. you need to add notify icon to your application and set the "ShowInTaskBar" property to False. now you have the notify icon in the system tray. my problem was I could not show the form if I double click on the notify icon. I tried to BringToFront() which works but it did not work under this situation. anyway here is the solution:

private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
this.Visible = true;
Show();
this.BringToFront();
this.Activate();
}

I know that bringtofront function does not work but I like to see my code this way more clear :) now Activate() works perfectly.

Thursday, February 14, 2008

Job interview

one time somebody asked me to write a code which will solve Fibonacci numbers. and I looked at the paper and after 5 secs. I told him to look at the Google this is the oldest question in the book.

I know there are some people who thinks programmer has to know this. I am not one of them actually I always like to write new things. who care the solution of Fibonacci in real world computer problems. I know what it is and how to solve it thats enough for me.

if you like to memorize that code or one of the fan of Fibonacci check this out:
http://www.hanselman.com/blog/TheWeeklySourceCode13FibonacciEdition.aspx

still I find c# 2 implementation better than others.

Friday, January 25, 2008

Mysql Charset C#

if you have any problem in inserting or updating values in utf8. there is easy way to do that. you need to add Charset=utf8 into your connection string example:
server=localhost;user id=fastfood;Charset=utf8;

Wednesday, October 17, 2007

?? C#

bu nedir şimdi diyorum kodu okurken aynen şöyle bir satır.
return ViewState["SortExpression"] as string ?? string.Empty;

bi an durakladım bu neki şimdi 3 senedir C# yazarım bu ne lan :D meğersem gayet güzel bir operatörmüş ()?: bu yapıyı andırıo ama bunda(??) koşul null olması.

şöyleki ?? işaretinin solundaki return ediliyor eğer null değilse. eğer işaretin solundaki null ise sağdaki return ediliyor nerde çağırıldıysa.

hazır başlamışken ()?: bunuda anlatim. bu çok eski bir yapıdır taa C de vardı :) ondan sonra hangi dil çıktıysa taşıdı desem yeridir. böle azcık satırlarımız olsun istediğimizde kullanırız parantezin içinedeki koşul true ise soru işaretinin sağındaki değilse iki nokta üst üstenin sağındaki return edilir. örnek:

string samsalak="1";
string dumbelek=(samsalak=="1")?"dertsiz":"tasasız";

bu durumda dumbelek dertsiz olacaktır ama samsalak ="1" demeseydik tasasız olcaktı :) demekki samsalaklar ne olursa olsun dumbelekler hep mutlu :D

Sunday, September 30, 2007

c# gui tools

c# da gtalk gibi bir form yapmak isterseniz veya şeker gibi user interface controlleri isterseniz denenebilcek güzel bir library.

http://www.codeplex.com/ASCENDNET

Monday, March 12, 2007

Session state in sql de tutulması (ASPState)

bu durum sessionun uzun ömürlü olmasını istediğinizde yapacağınız bişeydir ki
Session["eblek"]="gobalak";
dediğimizde veriler sql de tutulur ve timeout süresince orda kalırlar.

bunu kurmakda ayrı konudur hemen web.config den ayarlayınca olmazlar

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727>aspnet_regsql.exe -ssadd -C "Data
Source=localhost;User ID=***;Password=***"

şeklinde ayarlanırlar.
web.config dede yapılması gerekenler
<sessionState
mode="SQLServer"
sqlConnectionString="Data Source=localhost;User ID=***;Password=***"
cookieless="false"
timeout="1000" />

aha şimdi 1000 dakikalık sessionumuz ilen dakılabilirsiniz :)

Wednesday, February 14, 2007

sqldatasource kullanmak ve faydaları

öncelikle server browserdan sürükler bırakırsın çat diye oluşur insert ve inserted eventlerini yakalarsan mssql de son insert ettiğin id yi ala bilirsin .

protected void SqlDataSource1_Inserted(object sender, SqlDataSourceStatusEventArgs e)
{
int _inserted_maintemplate_id = Convert.ToInt32(((IDbDataParameter)e.Command.Parameters["@NewID"]).Value);

}
protected void SqlDataSource1_Inserting(object sender, SqlDataSourceCommandEventArgs e)
{
((IDbDataParameter)e.Command.Parameters["@NewID"]).Size = 4;
}

asp:parameter type="String" name="NewID" direction="Output"

bu son parametreyide eklemeyi unutma ama table da değişiklik yapıp insert dersen ve sql i değiştirmediysen anlamsız exception veriyor. table değişirse sqlini değiştirmeyi unuma.

playwright in junie

  { "mcpServers" : { "playwright" : { "command" : "npx" , "args" : [ ...