2009-06-24 2 views
2

나는 한 쪽 끝에 PHP 암호 해독 알고리즘을, 다른쪽에 .Net 암호화 알고리즘을 가지고있다. PHP 코드에서 암호 해독 목적으로 mcrypt_decrypt을 사용하고 있습니다. 닷넷에 mcrypt_encrypt을 찾고 있습니다.닷넷의 MCRYPT

$cipher_alg = MCRYPT_RIJNDAEL_128; 
$iv = mcrypt_create_iv (mcrypt_get_iv_size ($cipher_alg, MCRYPT_MODE_ECB), MCRYPT_RAND); 

$encrypted_string = mcrypt_encrypt ($cipher_alg, $sessionkey, $string, MCRYPT_MODE_CBC, $iv); 
$hex_encrypted_string = bin2hex ($encrypted_string); 

닷넷에서 mcrypt_encrypt의 동등한이 있습니까 : 더 구체적으로, 나는 닷넷로 변환 할 PHP 코드는 다음과 같다?

+0

'mcrypt_create_iv을()'+는'MCRYPT_MODE_ECB' 비싼'NOP'입니다. –

답변

3

나는 a solution in my blog으로 나왔습니다.

private static string CreateEncryptedString(string myString, string hexiv, string key) 
    { 
     RijndaelManaged alg = new RijndaelManaged(); 
     alg.Padding = PaddingMode.Zeros; 
     alg.Mode = CipherMode.CBC; 
     alg.BlockSize = 16 * 8; 
     alg.Key = ASCIIEncoding.UTF8.GetBytes(key); 
     alg.IV = StringToByteArray(hexiv); 
     ICryptoTransform encryptor = alg.CreateEncryptor(alg.Key, alg.IV); 

     MemoryStream msStream = new MemoryStream(); 
     CryptoStream mCSWriter = new CryptoStream(msStream, encryptor, CryptoStreamMode.Write); 
     StreamWriter mSWriter = new StreamWriter(mCSWriter); 
     mSWriter.Write(myString); 
     mSWriter.Flush(); 
     mCSWriter.FlushFinalBlock(); 

     var EncryptedByte = new byte[msStream.Length]; 
     msStream.Position = 0; 
     msStream.Read(EncryptedByte, 0, (int)msStream.Length); 

     return ByteArrayToHexString(EncryptedByte); 

    } 

    public static byte[] StringToByteArray(String hex) 
    { 
     int NumberChars = hex.Length; 
     byte[] bytes = new byte[NumberChars/2]; 
     for (int i = 0; i < NumberChars; i += 2) 
      bytes[i/2] = Convert.ToByte(hex.Substring(i, 2), 16); 
     return bytes; 
    } 

    public static string ByteArrayToHexString(byte[] ba) 
    { 
     StringBuilder hex = new StringBuilder(ba.Length * 2); 
     foreach (byte b in ba) 
      hex.AppendFormat("{0:x2}", b); 
     return hex.ToString(); 
    } 

주의해야 할 한 가지가있다 : 여기

는 발췌 한 것입니다. 키 크기는 16이어야합니다. 즉, 키 매개 변수는 16 자의 문자열이어야합니다. 그렇지 않으면 암호화가 작동하지 않고 CryptographicException을 던집니다. PHP는 말에

이 여기에 당신이 해독 할 방법은 다음과 같습니다

$cipher_alg = MCRYPT_RIJNDAEL_128; 
$decrypted_string = mcrypt_decrypt($cipher_alg, $key, 
$encrypted_string , MCRYPT_MODE_CBC, trim(hex2bin(trim($hexiv)))); 
1

직접적인 기능은 없지만 128 비트 Rijndael이 지원됩니다 (그리고 아마도 대부분의 다른 암호를 원할 것입니다). 자세한 내용 및 예는 Rijndael 클래스를 참조하십시오.

기본적으로 프레임 워크의 암호화 부분은 암호를 이름으로 지정하는 대신 기본 클래스 (CryptoStream, SymmetricAlgorithm 등)의 적절한 인스턴스를 지정하는 것을 기반으로하지만 필요한 작업을 수행 할 수 있어야합니다.

관련 문제