Exemple #1
0
 public static byte[] SHACalculate(byte[] data, SecurityPolicy policy)
 {
     using (System.Security.Cryptography.HashAlgorithm hashAlgorithm = UASecurity.HashAlgorithmForSecurityPolicy(policy))
     {
         return(hashAlgorithm.ComputeHash(data));
     }
 }
Exemple #2
0
        public static RSAParameters ImportRSAPublicKey(string buf)
        {
            RSAParameters rsaParameters = new RSACryptoServiceProvider().ExportParameters(false);

            byte[]       buffer       = Convert.FromBase64String(string.Join(string.Empty, ((IEnumerable <string>)buf.Split(Environment.NewLine.ToArray <char>())).Where <string>(line => !line.Trim().StartsWith("-")).ToArray <string>()));
            MemoryStream memoryStream = new MemoryStream();

            memoryStream.Write(buffer, 0, buffer.Length);
            memoryStream.Seek(0L, SeekOrigin.Begin);
            using (BinaryReader stream = new BinaryReader(memoryStream))
            {
                if (stream.ReadByte() != 48)
                {
                    return(rsaParameters);
                }

                UASecurity.DecodeLength(stream);
                byte[] numArray = UASecurity.DecodeIntBigEndian(stream);
                if (numArray.Length != 1 || numArray[0] > 0)
                {
                    return(rsaParameters);
                }

                rsaParameters.Modulus  = UASecurity.DecodeIntBigEndian(stream);
                rsaParameters.Exponent = UASecurity.DecodeIntBigEndian(stream);
                UASecurity.DecodeIntBigEndian(stream);
                UASecurity.DecodeIntBigEndian(stream);
                UASecurity.DecodeIntBigEndian(stream);
                UASecurity.DecodeIntBigEndian(stream);
                UASecurity.DecodeIntBigEndian(stream);
                UASecurity.DecodeIntBigEndian(stream);
            }
            return(rsaParameters);
        }
Exemple #3
0
 public static byte[] SymmetricSign(byte[] key, ArraySegment <byte> data, SecurityPolicy policy)
 {
     using (MemoryStream memoryStream = new MemoryStream(data.Array, data.Offset, data.Count))
     {
         return(UASecurity.HMACForSecurityPolicy(key, policy).ComputeHash(memoryStream));
     }
 }
Exemple #4
0
 public static byte[] SHACalculate(ArraySegment <byte> data, SecurityPolicy policy)
 {
     using (System.Security.Cryptography.HashAlgorithm hashAlgorithm = UASecurity.HashAlgorithmForSecurityPolicy(policy))
     {
         return(hashAlgorithm.ComputeHash(data.Array, data.Offset, data.Count));
     }
 }
Exemple #5
0
        public static byte[] RsaPkcs15Sha1_Encrypt(ArraySegment <byte> data, X509Certificate2 cert, SecurityPolicy policy)
        {
            bool useOaep = policy == SecurityPolicy.Basic256;

            var padMethod = UASecurity.PaddingMethodForSecurityPolicy(policy);
            int padSize   = UASecurity.PaddingSizeForMethod(padMethod);

            var rsa             = cert.PublicKey.Key as RSACryptoServiceProvider;
            int inputBlockSize  = GetPlainBlockSize(cert, useOaep);
            int outputBlockSize = rsa.KeySize / 8;

            if (data.Count % inputBlockSize != 0)
            {
                throw new Exception(string.Format("Input data is not a multiple of block size, {0}/{1}", data.Count, inputBlockSize));
            }

            var input = new byte[inputBlockSize];
            var ms    = new MemoryStream();

            for (int i = 0; i < data.Count; i += inputBlockSize)
            {
                Array.Copy(data.Array, data.Offset + i, input, 0, input.Length);
                var encoded = rsa.Encrypt(input, useOaep);
                ms.Write(encoded, 0, encoded.Length);
            }

            ms.Close();
            return(ms.ToArray());
        }
Exemple #6
0
        public static byte[] RsaPkcs15Sha_Decrypt(
            ArraySegment <byte> data,
            X509Certificate2 cert,
            RSA rsaPrivate,
            SecurityPolicy policy)
        {
            int cipherTextBlockSize = UASecurity.GetCipherTextBlockSize(cert);

            byte[] buffer1 = new byte[data.Count / cipherTextBlockSize * UASecurity.GetPlainBlockSize(cert, UASecurity.UseOaepForSecurityPolicy(policy))];
            int    length  = rsaPrivate.KeySize / 8;

            UASecurity.GetPlainBlockSize(cert, UASecurity.UseOaepForSecurityPolicy(policy));
            if ((uint)(data.Count % length) > 0U)
            {
                throw new Exception(string.Format("Input data is not a multiple of block size, {0}/{1}", data.Count, length));
            }

            MemoryStream memoryStream = new MemoryStream(buffer1);

            byte[] data1 = new byte[length];
            for (int offset = data.Offset; offset < data.Offset + data.Count; offset += length)
            {
                Array.Copy(data.Array, offset, data1, 0, data1.Length);
                byte[] buffer2 = rsaPrivate.Decrypt(data1, UASecurity.UseOaepForSecurityPolicy(policy));
                memoryStream.Write(buffer2, 0, buffer2.Length);
            }
            memoryStream.Close();
            return(buffer1);
        }
Exemple #7
0
        public static byte[] RsaPkcs15Sha_Encrypt(
            ArraySegment <byte> data,
            X509Certificate2 cert,
            SecurityPolicy policy)
        {
            RSA key            = cert.PublicKey.Key as RSA;
            int plainBlockSize = UASecurity.GetPlainBlockSize(cert, UASecurity.UseOaepForSecurityPolicy(policy));

            if ((uint)(data.Count % plainBlockSize) > 0U)
            {
                throw new Exception(string.Format("Input data is not a multiple of block size, {0}/{1}", data.Count, plainBlockSize));
            }

            byte[]       data1        = new byte[plainBlockSize];
            MemoryStream memoryStream = new MemoryStream();

            for (int index = 0; index < data.Count; index += plainBlockSize)
            {
                Array.Copy(data.Array, data.Offset + index, data1, 0, data1.Length);
                byte[] buffer = key.Encrypt(data1, UASecurity.UseOaepForSecurityPolicy(policy));
                memoryStream.Write(buffer, 0, buffer.Length);
            }
            memoryStream.Close();
            return(memoryStream.ToArray());
        }
Exemple #8
0
 public static bool RsaPkcs15Sha_VerifySigned(
     ArraySegment <byte> data,
     byte[] signature,
     X509Certificate2 cert,
     SecurityPolicy policy)
 {
     return((cert.PublicKey.Key as RSA).VerifyHash(UASecurity.HashAlgorithmForSecurityPolicy(policy).ComputeHash(data.Array, data.Offset, data.Count), signature, UASecurity.HashStrForSecurityPolicy(policy), RSASignaturePadding.Pkcs1));
 }
Exemple #9
0
 public static byte[] RsaPkcs15Sha_Sign(
     ArraySegment <byte> data,
     RSA privProvider,
     SecurityPolicy policy)
 {
     byte[] hash = UASecurity.HashAlgorithmForSecurityPolicy(policy).ComputeHash(data.Array, data.Offset, data.Count);
     return(privProvider.SignHash(hash, UASecurity.HashStrForSecurityPolicy(policy), RSASignaturePadding.Pkcs1));
 }
Exemple #10
0
        public static StatusCode SecureSymmetric(MemoryBuffer respBuf, int messageEncodedBlockStart, SLChannel.Keyset localKeyset, SLChannel.Keyset remoteKeyset, SecurityPolicy policy, MessageSecurityMode securityMode)
        {
            if (securityMode == MessageSecurityMode.None)
            {
                return(StatusCode.Good);
            }

            int sigSize = Sha1Size;

            if (securityMode >= MessageSecurityMode.SignAndEncrypt)
            {
                //int padSize2 = CalculateSymmetricPaddingSize(remoteKeyset.SymEncKey.Length, sigSize + respBuf.Position - messageEncodedBlockStart);
                int padSize = CalculateSymmetricPaddingSize(localKeyset.SymEncKey.Length, sigSize + respBuf.Position - messageEncodedBlockStart);

                byte paddingValue = (byte)((padSize - 1) & 0xFF);

                var appendPadding = new byte[padSize];
                for (int i = 0; i < padSize; i++)
                {
                    appendPadding[i] = paddingValue;
                }
                respBuf.Append(appendPadding);
            }

            int msgSize = respBuf.Position + sigSize;

            if (securityMode >= MessageSecurityMode.SignAndEncrypt)
            {
                msgSize = messageEncodedBlockStart + CalculateSymmetricEncryptedSize(localKeyset.SymEncKey.Length, msgSize - messageEncodedBlockStart);
            }

            if (msgSize >= respBuf.Capacity)
            {
                return(StatusCode.BadEncodingLimitsExceeded);
            }

            MarkUAMessageSize(respBuf, (UInt32)msgSize);

            var sig = UASecurity.SymmetricSign(localKeyset.SymSignKey,
                                               new ArraySegment <byte>(respBuf.Buffer, 0, respBuf.Position));

            respBuf.Append(sig);

            if (msgSize != respBuf.Position)
            {
                throw new Exception();
                return(StatusCode.BadInternalError);
            }

            if (securityMode >= MessageSecurityMode.SignAndEncrypt)
            {
                int encrLen = UASecurity.RijndaelEncryptInplace(
                    new ArraySegment <byte>(respBuf.Buffer, messageEncodedBlockStart, msgSize - messageEncodedBlockStart),
                    localKeyset.SymEncKey, localKeyset.SymIV);
            }

            return(StatusCode.Good);
        }
Exemple #11
0
 private static void EncodeIntBigEndian(BinaryWriter stream, byte[] value)
 {
     stream.Write((byte)2);
     UASecurity.EncodeLength(stream, value.Length);
     for (int index = 0; index < value.Length; ++index)
     {
         stream.Write(value[index]);
     }
 }
Exemple #12
0
        public static StatusCode SecureSymmetric(
            MemoryBuffer respBuf,
            int messageEncodedBlockStart,
            SLChannel.Keyset localKeyset,
            SLChannel.Keyset remoteKeyset,
            SecurityPolicy policy,
            MessageSecurityMode securityMode)
        {
            if (securityMode == MessageSecurityMode.None)
            {
                return(StatusCode.Good);
            }

            int num1 = UASecurity.SignatureSizeForSecurityPolicy(policy);

            if (securityMode >= MessageSecurityMode.SignAndEncrypt)
            {
                int    symmetricPaddingSize = UASecurity.CalculateSymmetricPaddingSize(localKeyset.SymEncKey.Length, num1 + respBuf.Position - messageEncodedBlockStart);
                byte   num2 = (byte)(symmetricPaddingSize - 1 & byte.MaxValue);
                byte[] Add  = new byte[symmetricPaddingSize];
                for (int index = 0; index < symmetricPaddingSize; ++index)
                {
                    Add[index] = num2;
                }

                respBuf.Append(Add);
            }
            int num3 = respBuf.Position + num1;

            if (securityMode >= MessageSecurityMode.SignAndEncrypt)
            {
                num3 = messageEncodedBlockStart + UASecurity.CalculateSymmetricEncryptedSize(localKeyset.SymEncKey.Length, num3 - messageEncodedBlockStart);
            }

            if (num3 >= respBuf.Capacity)
            {
                return(StatusCode.BadEncodingLimitsExceeded);
            }

            UASecurity.MarkUAMessageSize(respBuf, (uint)num3);
            byte[] Add1 = UASecurity.SymmetricSign(localKeyset.SymSignKey, new ArraySegment <byte>(respBuf.Buffer, 0, respBuf.Position), policy);
            respBuf.Append(Add1);
            if (num3 != respBuf.Position)
            {
                throw new Exception();
            }

            if (securityMode >= MessageSecurityMode.SignAndEncrypt)
            {
                UASecurity.RijndaelEncryptInplace(new ArraySegment <byte>(respBuf.Buffer, messageEncodedBlockStart, num3 - messageEncodedBlockStart), localKeyset.SymEncKey, localKeyset.SymIV);
            }

            return(StatusCode.Good);
        }
Exemple #13
0
        public static int CalculatePaddingSize(
            X509Certificate2 cert,
            SecurityPolicy policy,
            int position,
            int sigSize)
        {
            int plainBlockSize = UASecurity.GetPlainBlockSize(cert, UASecurity.UseOaepForSecurityPolicy(policy));
            int num            = plainBlockSize - (position + sigSize) % plainBlockSize;

            if (num < 0)
            {
                throw new Exception();
            }

            return(num);
        }
Exemple #14
0
        public static bool SHAVerify(byte[] data, byte[] hash, SecurityPolicy policy)
        {
            byte[] numArray = UASecurity.SHACalculate(data, policy);
            if (numArray.Length != hash.Length)
            {
                return(false);
            }

            for (int index = 0; index < numArray.Length; ++index)
            {
                if (hash[index] != numArray[index])
                {
                    return(false);
                }
            }
            return(true);
        }
Exemple #15
0
        public static int SymmetricSignatureKeySizeForSecurityPolicy(SecurityPolicy policy)
        {
            switch (policy)
            {
            case SecurityPolicy.Basic256:
                return(24);

            case SecurityPolicy.Basic128Rsa15:
                return(UASecurity.SymmetricKeySizeForSecurityPolicy(policy, -1));

            case SecurityPolicy.Basic256Sha256:
                return(32);

            default:
                throw new Exception();
            }
        }
Exemple #16
0
        public static int CalculateEncryptedSize(
            X509Certificate2 cert,
            int messageSize,
            UASecurity.PaddingAlgorithm paddingAlgorithm)
        {
            if (!(cert.PublicKey.Key is RSA))
            {
                throw new Exception("Could not create RSA");
            }

            int num1 = UASecurity.PaddingSizeForMethod(paddingAlgorithm);
            int num2 = UASecurity.CalculatePublicKeyLength(cert) / 8;

            if (num2 < num1)
            {
                throw new Exception();
            }

            int num3 = num2 - num1;

            return((messageSize + num3 - 1) / num3 * num2);
        }
Exemple #17
0
        private static byte[] DecodeIntBigEndian(BinaryReader stream)
        {
            if (stream.ReadByte() != 2)
            {
                return(null);
            }

            int length = UASecurity.DecodeLength(stream);

            if (length < 0)
            {
                return(null);
            }

            byte[] numArray = new byte[length];
            for (int index = 0; index < length; ++index)
            {
                numArray[index] = stream.ReadByte();
            }

            return(numArray);
        }
Exemple #18
0
        public static string ExportRSAPublicKey(RSAParameters parameters)
        {
            MemoryStream memoryStream1 = new MemoryStream();

            using (StreamWriter streamWriter = new StreamWriter(memoryStream1))
            {
                using (MemoryStream memoryStream2 = new MemoryStream())
                {
                    BinaryWriter stream1 = new BinaryWriter(memoryStream2);
                    stream1.Write((byte)48);
                    using (MemoryStream memoryStream3 = new MemoryStream())
                    {
                        BinaryWriter stream2 = new BinaryWriter(memoryStream3);
                        UASecurity.EncodeIntBigEndian(stream2, new byte[1]);
                        UASecurity.EncodeIntBigEndian(stream2, parameters.Modulus);
                        UASecurity.EncodeIntBigEndian(stream2, parameters.Exponent);
                        UASecurity.EncodeIntBigEndian(stream2, parameters.Exponent);
                        UASecurity.EncodeIntBigEndian(stream2, parameters.Exponent);
                        UASecurity.EncodeIntBigEndian(stream2, parameters.Exponent);
                        UASecurity.EncodeIntBigEndian(stream2, parameters.Exponent);
                        UASecurity.EncodeIntBigEndian(stream2, parameters.Exponent);
                        UASecurity.EncodeIntBigEndian(stream2, parameters.Exponent);
                        int length = (int)memoryStream3.Length;
                        UASecurity.EncodeLength(stream1, length);
                        stream1.Write(memoryStream3.ToArray(), 0, length);
                    }
                    char[] charArray = Convert.ToBase64String(memoryStream2.ToArray(), 0, (int)memoryStream2.Length).ToCharArray();
                    streamWriter.WriteLine("-----BEGIN RSA PUBLIC KEY-----");
                    for (int index = 0; index < charArray.Length; index += 64)
                    {
                        streamWriter.WriteLine(charArray, index, Math.Min(64, charArray.Length - index));
                    }

                    streamWriter.WriteLine("-----END RSA PUBLIC KEY-----");
                }
            }
            return(Encoding.ASCII.GetString(memoryStream1.ToArray()));
        }
Exemple #19
0
        public static byte[] PSHA(byte[] secret, byte[] seed, int length, SecurityPolicy policy)
        {
            HMAC hmac = UASecurity.HMACForSecurityPolicy(secret, policy);
            int  val1 = UASecurity.SignatureSizeForSecurityPolicy(policy);

            byte[] hash1  = hmac.ComputeHash(seed);
            byte[] buffer = new byte[val1 + seed.Length];
            Array.Copy(hash1, buffer, hash1.Length);
            Array.Copy(seed, 0, buffer, hash1.Length, seed.Length);
            byte[] numArray         = new byte[length];
            int    destinationIndex = 0;

            while (destinationIndex < length)
            {
                byte[] hash2   = hmac.ComputeHash(buffer);
                int    length1 = Math.Min(val1, length - destinationIndex);
                Array.Copy(hash2, 0, numArray, destinationIndex, length1);
                destinationIndex += length1;
                hash1             = hmac.ComputeHash(hash1);
                Array.Copy(hash1, buffer, hash1.Length);
            }
            return(numArray);
        }
Exemple #20
0
        public static StatusCode UnsecureSymmetric(MemoryBuffer recvBuf, uint tokenID, uint?prevTokenID, int messageEncodedBlockStart, SLChannel.Keyset localKeyset, SLChannel.Keyset[] remoteKeysets, SecurityPolicy policy, MessageSecurityMode securityMode, out int decrSize)
        {
            decrSize = -1;
            int restorePos = recvBuf.Position;

            byte   type = 0;
            uint   messageSize = 0;
            UInt32 secureChannelId, securityTokenId, securitySeqNum, securityReqId;

            if (!recvBuf.Decode(out type))
            {
                return(StatusCode.BadDecodingError);
            }
            if (!recvBuf.Decode(out messageSize))
            {
                return(StatusCode.BadDecodingError);
            }
            if (!recvBuf.Decode(out secureChannelId))
            {
                return(StatusCode.BadDecodingError);
            }
            if (!recvBuf.Decode(out securityTokenId))
            {
                return(StatusCode.BadDecodingError);
            }

            int keysetIdx = -1;

            if (tokenID == securityTokenId)
            {
                keysetIdx = 0;
            }
            else if (prevTokenID.HasValue && prevTokenID.Value == securityTokenId)
            {
                keysetIdx = 1;
            }
            else
            {
                return(StatusCode.BadSecureChannelTokenUnknown);
            }

            //UInt32 respDecodeSize = messageSize;
            if (securityMode == MessageSecurityMode.SignAndEncrypt)
            {
                try
                {
                    decrSize = UASecurity.RijndaelDecryptInplace(
                        new ArraySegment <byte>(recvBuf.Buffer, messageEncodedBlockStart, (int)messageSize - messageEncodedBlockStart),
                        remoteKeysets[keysetIdx].SymEncKey, remoteKeysets[keysetIdx].SymIV) + messageEncodedBlockStart;

                    //respDecodeSize = (UInt32)(messageEncodedBlockStart + decrSize);
                }
                catch
                {
                    return(StatusCode.BadSecurityChecksFailed);
                }
            }

            if (securityMode >= MessageSecurityMode.Sign)
            {
                try
                {
                    int sigSize = SignatureSizeForSecurityPolicy(policy);
                    var sigData = new ArraySegment <byte>(recvBuf.Buffer, 0, (int)messageSize - sigSize);

                    var sig       = new ArraySegment <byte>(recvBuf.Buffer, (int)messageSize - sigSize, sigSize).ToArray();
                    var sigExpect = UASecurity.SymmetricSign(remoteKeysets[keysetIdx].SymSignKey, sigData, policy);

                    if (sig.Length != sigExpect.Length)
                    {
                        return(StatusCode.BadSecurityChecksFailed);
                    }

                    for (int i = 0; i < sig.Length; i++)
                    {
                        if (sig[i] != sigExpect[i])
                        {
                            return(StatusCode.BadSecurityChecksFailed);
                        }
                    }

                    byte padValue = (byte)(recvBuf.Buffer[messageSize - sigSize - 1] + 1);
                    if (decrSize > 0)
                    {
                        decrSize -= sigSize;
                        decrSize -= (int)padValue;
                        if (decrSize <= 0)
                        {
                            return(StatusCode.BadSecurityChecksFailed);
                        }
                    }
                }
                catch
                {
                    return(StatusCode.BadSecurityChecksFailed);
                }
            }

            if (!recvBuf.Decode(out securitySeqNum))
            {
                return(StatusCode.BadDecodingError);
            }
            if (!recvBuf.Decode(out securityReqId))
            {
                return(StatusCode.BadDecodingError);
            }

            recvBuf.Position = restorePos;

            return(StatusCode.Good);
        }
Exemple #21
0
 public static byte[] GenerateRandomBits(int numBits)
 {
     return(UASecurity.GenerateRandomBytes((numBits + 7) / 8));
 }
Exemple #22
0
        public static StatusCode UnsecureSymmetric(
            MemoryBuffer recvBuf,
            uint tokenID,
            uint?prevTokenID,
            int messageEncodedBlockStart,
            SLChannel.Keyset localKeyset,
            SLChannel.Keyset[] remoteKeysets,
            SecurityPolicy policy,
            MessageSecurityMode securityMode,
            out int decrSize)
        {
            decrSize = -1;
            int position = recvBuf.Position;

            if (!recvBuf.Decode(out byte v1) || !recvBuf.Decode(out uint v2) || (!recvBuf.Decode(out uint _) || !recvBuf.Decode(out uint v3)))
            {
                return(StatusCode.BadDecodingError);
            }

            int index1;

            if ((int)tokenID == (int)v3)
            {
                index1 = 0;
            }
            else
            {
                if (!prevTokenID.HasValue || (int)prevTokenID.Value != (int)v3)
                {
                    return(StatusCode.BadSecureChannelTokenUnknown);
                }

                index1 = 1;
            }
            if (securityMode == MessageSecurityMode.SignAndEncrypt)
            {
                try
                {
                    decrSize = UASecurity.RijndaelDecryptInplace(new ArraySegment <byte>(recvBuf.Buffer, messageEncodedBlockStart, (int)v2 - messageEncodedBlockStart), remoteKeysets[index1].SymEncKey, remoteKeysets[index1].SymIV) + messageEncodedBlockStart;
                }
                catch
                {
                    return(StatusCode.BadSecurityChecksFailed);
                }
            }
            else
            {
                decrSize = (int)v2;
            }

            if (securityMode >= MessageSecurityMode.Sign)
            {
                try
                {
                    int count = UASecurity.SignatureSizeForSecurityPolicy(policy);
                    ArraySegment <byte> data = new ArraySegment <byte>(recvBuf.Buffer, 0, (int)v2 - count);
                    byte[] array             = new ArraySegment <byte>(recvBuf.Buffer, (int)v2 - count, count).ToArray();
                    byte[] numArray          = UASecurity.SymmetricSign(remoteKeysets[index1].SymSignKey, data, policy);
                    if (array.Length != numArray.Length)
                    {
                        return(StatusCode.BadSecurityChecksFailed);
                    }

                    for (int index2 = 0; index2 < array.Length; ++index2)
                    {
                        if (array[index2] != numArray[index2])
                        {
                            return(StatusCode.BadSecurityChecksFailed);
                        }
                    }
                    byte num = securityMode == MessageSecurityMode.SignAndEncrypt ? (byte)(recvBuf.Buffer[v2 - count - 1L] + 1U) : (byte)0;
                    if (decrSize > 0)
                    {
                        decrSize -= count;
                        decrSize -= num;
                        if (decrSize <= 0)
                        {
                            return(StatusCode.BadSecurityChecksFailed);
                        }
                    }
                }
                catch
                {
                    return(StatusCode.BadSecurityChecksFailed);
                }
            }
            if (!recvBuf.Decode(out uint _) || !recvBuf.Decode(out uint _))
            {
                return(StatusCode.BadDecodingError);
            }

            recvBuf.Position = position;
            return(StatusCode.Good);
        }
Exemple #23
0
 public static int GetSignatureLength(X509Certificate2 cert, SecurityPolicy policy)
 {
     return(UASecurity.GetSignatureLength(cert));
 }
Exemple #24
0
 public static int CalculateSignatureSize(X509Certificate2 cert)
 {
     return(UASecurity.CalculateSignatureSize(cert.PublicKey.Key as RSA));
 }