문제

나는 암호를 사용하고 싶다 코드플렉스의 휴대용 클래스 라이브러리 컨트리브 프로젝트 그러나 내가 그것을 어떻게 사용할 수 있는지에 대한 문서를 찾지 못했습니다.

나는 래퍼 클래스를 만들고 싶어 Encrypt 그리고 Decrypt 그 안에 메소드가 있고 이 래퍼 클래스가 휴대용 클래스 라이브러리에 존재하기를 원합니다.나는 참조했다 Portable.Runtime 그리고 Portable.Security.Cryptography 이 프로젝트에서이 올바른가요?

그런 다음 <url>,윈도우 폰 및 메트로 프로젝트 내에서 래퍼를 사용하고 싶습니다.이 프로젝트에서 내 래퍼 프로젝트를 참조합니다, Portable.Runtime, Portable.Security.Cryptography 그리고 해당 휴대용 프로젝트 즉. Portable.Desktop, Portable.Phone 또는 Portable.WindowsStore.이 올바른가요?

그러나 래퍼 클래스를 사용하려고 할 때 충돌하는 네임 스페이스 오류가 발생합니다.이 오류 및 내 래퍼 클래스입니다:

유형 System.Security.Cryptography.AesManaged 둘 다 존재합니다 C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\Profile\Client\System.Core.dll 그리고 C:\Downloads\PclContrib\bin\Debug\Portable.Security.Cryptography.dll

public sealed class SymmetricCryptography<T> where T : SymmetricAlgorithm, new()
{
    private readonly T provider = new T();
    private readonly UTF8Encoding utf8 = new UTF8Encoding();

    private byte[] key;
    private byte[] iv;

    public byte[] Key
    {
        get { return this.key; }
    }

    public byte[] IV
    {
        get { return this.iv; }
    }

    public SymmetricCryptography()
    {
        this.key = this.provider.Key;
        this.iv = this.provider.IV;
    }

    public SymmetricCryptography(byte[] key, byte[] iv)
    {
        this.key = key;
        this.iv = iv;
    }

    public SymmetricCryptography(string password, string salt)
    {
        Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(password, this.utf8.GetBytes(salt));
        this.key = deriveBytes.GetBytes(this.provider.KeySize >> 3);
        this.iv = deriveBytes.GetBytes(16);
    }

    public SymmetricCryptography(string password, string salt, int iterations)
    {
        Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(password, this.utf8.GetBytes(salt), iterations);
        this.key = deriveBytes.GetBytes(this.provider.KeySize >> 3);
        this.iv = deriveBytes.GetBytes(16);
    }

    public byte[] Encrypt(byte[] input)
    {
        return this.Encrypt(input, this.key, this.iv);
    }

    public byte[] Encrypt(byte[] input, byte[] key, byte[] iv)
    {
        return this.Transform(
            input,
            this.provider.CreateEncryptor(key, iv));
    }

    public byte[] Decrypt(byte[] input)
    {
        return this.Decrypt(input, this.key, this.iv);
    }

    public byte[] Decrypt(byte[] input, byte[] key, byte[] iv)
    {
        return this.Transform(
            input,
            this.provider.CreateDecryptor(key, iv));
    }

    public string Encrypt(string text)
    {
        return this.Encrypt(text, this.key, this.iv);
    }

    public string Encrypt(string text, byte[] key, byte[] iv)
    {
        byte[] output = this.Transform(
            this.utf8.GetBytes(text),
            this.provider.CreateEncryptor(key, iv));
        return Convert.ToBase64String(output);
    }

    public string Decrypt(string text)
    {
        return this.Decrypt(text, this.key, this.iv);
    }

    public string Decrypt(string text, byte[] key, byte[] iv)
    {
        byte[] output = this.Transform(
            Convert.FromBase64String(text),
            this.provider.CreateDecryptor(key, iv));
        return this.utf8.GetString(output, 0, output.Length);
    }

    public void Encrypt(Stream input, Stream output)
    {
        this.Encrypt(input, output, this.key, this.iv);
    }

    public void Encrypt(Stream input, Stream output, byte[] key, byte[] iv)
    {
        this.TransformStream(true, ref input, ref output, key, iv);
    }

    public void Decrypt(Stream input, Stream output)
    {
        this.Decrypt(input, output, this.key, this.iv);
    }

    public void Decrypt(Stream input, Stream output, byte[] key, byte[] iv)
    {
        this.TransformStream(false, ref input, ref output, key, iv);
    }

    private byte[] Transform(
        byte[] input,
        ICryptoTransform cryptoTransform)
    {
        byte[] result;

        using (MemoryStream memoryStream = new MemoryStream())
        {
            using (CryptoStream cryptStream = new CryptoStream(
                memoryStream,
                cryptoTransform,
                CryptoStreamMode.Write))
            {
                cryptStream.Write(input, 0, input.Length);
                cryptStream.FlushFinalBlock();
                memoryStream.Position = 0;
                result = memoryStream.ToArray();
            }
        }

        return result;
    }

    private void TransformStream(bool encrypt, ref Stream input, ref Stream output, byte[] key, byte[] iv)
    {
        // defensive argument checking
        if (input == null)
        {
            throw new ArgumentNullException("input");
        }

        if (output == null)
        {
            throw new ArgumentNullException("output");
        }

        if (!input.CanRead)
        {
            throw new ArgumentException("Unable to read from the input Stream.", "input");
        }

        if (!output.CanWrite)
        {
            throw new ArgumentException("Unable to write to the output Stream.", "output");
        }

        // make the buffer just large enough for 
        // the portion of the stream to be processed
        byte[] inputBuffer = new byte[input.Length - input.Position];
        // read the stream into the buffer
        input.Read(inputBuffer, 0, inputBuffer.Length);
        // transform the buffer
        byte[] outputBuffer = encrypt ? Encrypt(inputBuffer, key, iv)
                                        : Decrypt(inputBuffer, key, iv);
        // write the transformed buffer to our output stream 
        output.Write(outputBuffer, 0, outputBuffer.Length);
    }
}
도움이 되었습니까?

해결책 3

그것은 암호화 알고리즘에 대한 내 일반 래퍼가 문제를 일으키는 것으로 밝혀졌습니다.대칭각수리듬은 실제 대칭각수리듬을 위한 래퍼입니다.내 래퍼 클래스를 비 제네릭으로 만들면 다음과 같이 작동합니다:

public sealed class AesManagedSymmetricCryptography : SymmetricCryptography<AesManaged>
{
    #region Constructors

    public AesManagedSymmetricCryptography()
    {
    }

    public AesManagedSymmetricCryptography(byte[] key, byte[] iv)
        : base(key, iv)
    {
    }

    public AesManagedSymmetricCryptography(string password, string salt)
        : base(password, salt)
    {
    }

    public AesManagedSymmetricCryptography(string password, string salt, int iterations)
        : base(password, salt, iterations)
    {
    }

    #endregion
}

다른 팁

문서는 조금 부족,하지만 난이 밖으로 전화 제품소개:

내 플랫폼별 프로젝트와 피클론트립의 유형을 공유할 수 있습니까? 아니,현재.그러나,이 유형의 자신의 플랫폼 특정 대응,런타임 및 같은 느낌 컴파일러는 그들을 완전히 다른 유형으로 볼 것입니다.우리가 가지고 있는 동안 이 작업을 만드는 방법에 대한 몇 가지 아이디어,이것은 우리가하지 않습니다 기능입니다 짧은 기간에 대 한 보고.

다음 <url> 코드는 데스크톱 구현에서 작동합니다.먼저 포터블에 대한 참조를 추가하십시오.데스크탑 및 휴대용.보안.암호학보호된 데이터

   private void button2_Click(object sender, EventArgs e)
    {
        String encrypted = PCL.CentralClass.Encrypt("yo");
        String decreypted = PCL.CentralClass.Decrypt(encrypted);
        //PCL.CentralClass.
    }
    //https://pclcontrib.codeplex.com/documentation?FocusElement=Comment
    //\Source\Portable.Security.Cryptography.ProtectedData\Security\Cryptography\ProtectedData.cs

    static byte[] GetBytes(string str)
    {
        byte[] bytes = new byte[str.Length * sizeof(char)];
        System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
        return bytes;
    }

    static string GetString(byte[] bytes)
    {
        char[] chars = new char[bytes.Length / sizeof(char)];
        System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
        return new string(chars);
    }

    public static String Encrypt(String strEncrypt)
    {
        byte[] userData = GetBytes(strEncrypt);
        byte[] optionalEntropy = null;
        byte[] x = System.Security.Cryptography.ProtectedData.Protect(userData, optionalEntropy);
        return GetString(x);
    }
    public static String Decrypt(String strDecrypt)
    {
        byte[] encryptedData = GetBytes(strDecrypt);
        byte[] optionalEntropy = null;
        byte[] x = System.Security.Cryptography.ProtectedData.Unprotect(encryptedData, optionalEntropy);
        return GetString(x); ;
    }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top