2013-08-08 2 views
2

길이가 0에서 15 사이의 사용자 정의 문자열을 128 비트 문자열로 강제 변환하려고하므로 AesCryptoServiceProvider 키로 사용할 수 있습니다. 나는 여러 전략을 주변에 바이올린을 시도하고 다음과 만난다사용자 정의 문자열에서 128 비트 문자열

는 :

 if (stringToConvert.Length > 16) 
     { 
      StringBuilder sB = new StringBuilder(); 
      char[] chA = stringToConvert.ToCharArray(); 
      int chAMaxLength = chA.Length; 

      for (int i = 0; i < 16; i++) 
      { 
       if (i <= chAMaxLength) 
       { 
        sB.Append(chA[i]); 
       } 
      } 
     } 

나는 (= 128 16 * 8) 정확히 16 자 문자열이 필요합니다.

저는 이제이 문제를 해결하기 위해 손을 뻗어 야합니다.
간단하게 보일 수 있으면 미리 사과드립니다.

예 :
asd이 될 것
asdasdasdasdasda

+0

; '?? – SynerCoder

+0

변환 할 문자열의 길이가 0 .. 15 자이고 16보다 길지 않으므로 if가 입력되지 않습니다. – ThaMe90

+0

chA가 5 자이면 최종 결과는 5 자입니다. – TheGeekZn

답변

1
StringBuilder b = new StringBuilder(); 
for (int i = 0; i < 8; i++) 
{ 
    b.Append(stringToConvert[i % stringToConvert.Length]); 
} 
stringToConvert = b.ToString(); 
byte[] key = Encoding.Unicode.GetBytes(stringToConvert);//key size is 16 bytes = 128 bits 

(A StringBuilder없이) 더 나은 :

byte[] key = new byte[16]; 
for (int i = 0; i < 16; i+=2) 
{ 
    byte[] unicodeBytes = BitConverter.GetBytes(stringToConvert[i % stringToConvert.Length]); 
    Array.Copy(unicodeBytes, 0, key, i, 2); 
} 
+0

당신은 훌륭합니다. – TheGeekZn

0

당신은 단순히 당신의 문자열의 해시를 CALC (16로 크기를 조정 SHA1이 20 바이트이기 때문에)

string password = "shortstring"; 

using (SHA1 sha = new SHA1CryptoServiceProvider()) 
{ 
    // This is one implementation of the abstract class SHA1. 
    byte[] result = sha.ComputeHash(Encoding.UTF8.GetBytes(password)); 
    Array.Resize(ref result, 16); 
} 

이것은 여전히 ​​잘못되었습니다. 암호를 강화하는 방법을 설명하는 Rfc2898을 사용해야합니다. 결국 기본 원칙은 이전 해시 함수의 결과에 해시 함수를 반복적으로 호출하는 것입니다. 끝 ,,,`stringToConvert sB.ToString =()에

string password = "shortstring"; 
byte[] salt = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7 }; // this is fixed... It would be better you used something different for each user 

// You can raise 1000 to greater numbers... more cycles = more security. Try 
// balancing speed with security. 
Rfc2898DeriveBytes pwdGen = new Rfc2898DeriveBytes(password, salt, 1000); 

// generate key 
byte[] key = pwdGen.GetBytes(16); 
+0

입력 해 주셔서 감사합니다. 그러나 암호의 강도를 생성 할 필요가 없습니다. 'a'조차도 괜찮을 것입니다. D 나는 확실히 이것을 미래를 염두에 두겠습니다. – TheGeekZn