2012-11-21 2 views
1

C#에서 문자열의 간단한 코딩과 디코딩을 구현해야합니다.C#, 내부에 체크섬을 사용하여 간단한 코드로 인 코드/디코드

"높은 비밀"암호화가 필요하지 않으므로 체크섬이있는 즉시 간단한 인코딩이 가능합니다.

코드의 한 인스턴스 내에서 쉬운 양방향 인코딩 - 디코딩이 필요합니다. 인코딩과 디코딩을 모두 수행하는 프로그램이 하나뿐이므로 "보안 키"는 모두 하드 코드 될 수 있습니다.

인코딩 결과는 영숫자 (텍스트) 여야합니다. 필드는 텍스트 CSV 테이블 인 파일에 참여하므로 이진 데이터 (비서, 비대칭)는 피해야합니다.

일관성을 검사 할 수있는 코드 (컨트롤 문자/체크섬을 포함해야 함)가 필요하므로이 필드가 제 3 자에 의해 변경되지 않고 유효하게 디코딩 가능하다는 것을 알 수 있습니다. (신용 카드 번호의 제어 숫자와 같은 것).

코드 길이는 원시 문자열의 길이와 대략 비슷해야합니다 (5-10 배가 아님).

C#에서 최고의 라이브러리를 알려 주시면 감사하겠습니다. 미리 감사드립니다.

+0

"인코딩"의 사용/"디코드"- 나는 분명히 할 수있다 : 우리는 서명과 함께 아마도/여기에 "해독" "암호화"에 대해 얘기하고 ? 대부분의 암호화는 raw 바이트 스트림을 출력하지만, 문자열로 표현하기 위해 base-64로 인코딩 할 수 있습니다 (비트가 더 클 것입니다) –

+0

yes, encrypt 및 checksumming (문자열이 변경되지 않았 음을 알고 있습니다) . Base64 bin-to-text는 문제가 없습니다. –

+0

나는 당신이 암호화와 암호화를 혼란스럽게 생각한다고 생각합니다. 암호화가 필요합니다. 좋은 답변을 반복하기보다는 http://stackoverflow.com/questions/202011/encrypt-decrypt-string-in-net 및 http://stackoverflow.com/questions/165808/simple-2-way-encryption- for-c-sharp – Kami

답변

2

RC4에서

방법은 암호화/복호화를 위해 용이하게 구현 될 수있는 간단한 알고리즘이다. AES만큼 안전하지는 않지만, 상황에 따라 AES 보안이 필요하지 않은 것으로 보입니다. 다음은

public static class RC4 
{ 
    public static string Encrypt(string key, string data) 
    { 
     Encoding unicode = Encoding.Unicode; 

     return Convert.ToBase64String(Encrypt(unicode.GetBytes(key), unicode.GetBytes(data))); 
    } 

    public static string Decrypt(string key, string data) 
    { 
     Encoding unicode = Encoding.Unicode; 

     return unicode.GetString(Encrypt(unicode.GetBytes(key), Convert.FromBase64String(data))); 
    } 

    public static byte[] Encrypt(byte[] key, byte[] data) 
    { 
     return EncryptOutput(key, data).ToArray(); 
    } 

    public static byte[] Decrypt(byte[] key, byte[] data) 
    { 
     return EncryptOutput(key, data).ToArray(); 
    } 

    private static byte[] EncryptInitalize(byte[] key) 
    { 
     byte[] s = Enumerable.Range(0, 256) 
     .Select(i => (byte)i) 
     .ToArray(); 

     for (int i = 0, j = 0; i < 256; i++) 
     { 
     j = (j + key[i % key.Length] + s[i]) & 255; 

     Swap(s, i, j); 
     } 

     return s; 
    } 

    private static IEnumerable<byte> EncryptOutput(byte[] key, IEnumerable<byte> data) 
    { 
     byte[] s = EncryptInitalize(key); 

     int i = 0; 
     int j = 0; 

     return data.Select((b) => 
     { 
     i = (i + 1) & 255; 
     j = (j + s[i]) & 255; 

     Swap(s, i, j); 

     return (byte)(b^s[(s[i] + s[j]) & 255]); 
     }); 
    } 

    private static void Swap(byte[] s, int i, int j) 
    { 
     byte c = s[i]; 

     s[i] = s[j]; 
     s[j] = c; 
    } 
} 
this site에서 .NET에서 RC4의 구현입니다
1

나는이 코드를 rijndael로 암호화/해독하는 데 사용했습니다. 암호화 된 문자열을 건 드리면 CryptographicException을 던집니다. http://www.codeproject.com/Articles/5719/Simple-encrypting-and-decrypting-data-in-C

public string Encrypt(string clearText, string Password) 
    { 
     //Convert text to bytes 
     byte[] clearBytes = 
      System.Text.Encoding.Unicode.GetBytes(clearText); 

     //We will derieve our Key and Vectore based on following 
     //password and a random salt value, 13 bytes in size. 
     PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, 
      new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 
     0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76}); 

     byte[] encryptedData = Encrypt(clearBytes, 
       pdb.GetBytes(32), pdb.GetBytes(16)); 

     return Convert.ToBase64String(encryptedData); 
    } 

    //Call following function to decrypt data 
    public string Decrypt(string cipherText, string Password) 
    { 
     //Convert base 64 text to bytes 
     byte[] cipherBytes = Convert.FromBase64String(cipherText); 

     //We will derieve our Key and Vectore based on following 
     //password and a random salt value, 13 bytes in size. 
     PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, 
      new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 
     0x64, 0x76, 0x65, 0x64, 0x65, 0x76}); 
     byte[] decryptedData = Decrypt(cipherBytes, 
      pdb.GetBytes(32), pdb.GetBytes(16)); 

     //Converting unicode string from decrypted data 
     return Encoding.Unicode.GetString(decryptedData); 
    } 

    public byte[] Encrypt(byte[] clearData, byte[] Key, byte[] IV) 
    { 
     byte[] encryptedData; 
     //Create stream for encryption 
     using (MemoryStream ms = new MemoryStream()) 
     { 
      //Create Rijndael object with key and vector 
      using (Rijndael alg = Rijndael.Create()) 
      { 
       alg.Key = Key; 
       alg.IV = IV; 
       //Forming cryptostream to link with data stream. 
       using (CryptoStream cs = new CryptoStream(ms, 
        alg.CreateEncryptor(), CryptoStreamMode.Write)) 
       { 
        //Write all data to stream. 
        cs.Write(clearData, 0, clearData.Length); 
       } 
       encryptedData = ms.ToArray(); 
      } 
     } 
     return encryptedData; 
    } 

    public byte[] Decrypt(byte[] cipherData, byte[] Key, byte[] IV) 
    { 
     byte[] decryptedData; 
     //Create stream for decryption 
     using (MemoryStream ms = new MemoryStream()) 
     { 
      //Create Rijndael object with key and vector 
      using (Rijndael alg = Rijndael.Create()) 
      { 
       alg.Key = Key; 
       alg.IV = IV; 
       //Forming cryptostream to link with data stream. 
       using (CryptoStream cs = new CryptoStream(ms, 
        alg.CreateDecryptor(), CryptoStreamMode.Write)) 
       { 
        //Write all data to stream. 
        cs.Write(cipherData, 0, cipherData.Length); 
       } 
       decryptedData = ms.ToArray(); 
      } 
     } 
     return decryptedData; 
    } 
+1

암호화 체크섬 대신 패딩에 따라 다릅니다. PasswordDeriveBytes를 사용하는 것은 권장되지 않으며 해시 함수 (SHA-1의 경우 160 비트)보다 큰 출력에는 안전하지 않습니다. –

관련 문제