Example #1
0
        public static byte[] Create(byte[] Message, byte[] Nonce, byte[] SecretKey, byte[] PublicKey)
        {
            if (SecretKey == null || SecretKey.Length != GetSecretKeyBytesLength())
            {
                throw new ArgumentException("Error: Secret key must be " + GetSecretKeyBytesLength() + " bytes in length");
            }

            if (PublicKey == null || PublicKey.Length != GetPublicKeyBytesLength())
            {
                throw new ArgumentException("Error: Public key must be " + GetPublicKeyBytesLength() + " bytes in length");
            }

            if (Nonce == null || Nonce.Length != GetNonceBytesLength())
            {
                throw new ArgumentException("Error: Nonce must be " + GetNonceBytesLength() + " bytes in length");
            }

            byte[] CipherText = new byte[Message.Length + GetMACBytesLength()];
            int    ret        = SodiumPublicKeyBoxLibrary.crypto_box_easy(CipherText, Message, Message.Length, Nonce, PublicKey, SecretKey);

            GCHandle MyGeneralGCHandle = new GCHandle();

            MyGeneralGCHandle = GCHandle.Alloc(SecretKey, GCHandleType.Pinned);
            SodiumSecureMemory.MemZero(MyGeneralGCHandle.AddrOfPinnedObject(), SecretKey.Length);
            MyGeneralGCHandle.Free();

            MyGeneralGCHandle = GCHandle.Alloc(PublicKey, GCHandleType.Pinned);
            SodiumSecureMemory.MemZero(MyGeneralGCHandle.AddrOfPinnedObject(), PublicKey.Length);
            MyGeneralGCHandle.Free();

            if (ret != 0)
            {
                throw new CryptographicException("Failed to create PublicKeyBox");
            }

            return(CipherText);
        }