public EncryptionHelper()
 {
     buffer = new byte[1000];
     NativeLibsodium.sodium_init();
     _SetKeys();
     //GenerateNewKey();
 }
예제 #2
0
파일: Encrypt.cs 프로젝트: Coflnet/cloud
        public static byte[] EncryptData(byte[] data, byte[] key)
        {
            long cipherTextLength = data.Length + 16;

            byte[] cipherText = new byte[cipherTextLength];
            byte[] nonce      = StreamEncryption.GetRandomBytes(X_NONC_ESIZE);

            int result = NativeLibsodium.crypto_aead_xchacha20poly1305_ietf_encrypt(
                cipherText,
                out cipherTextLength,
                data,
                data.Length,
                null, 0, null,
                nonce,
                key);

            if (result != 0)
            {
                throw new EncryptionError();
            }

            byte[] cipherTextWithNonce = ConcatNonceAndCipherText(nonce, cipherText);

            return(cipherTextWithNonce);
        }
예제 #3
0
        /// <summary>
        /// Decrypt the specified ciphertext, with key and nonce.
        /// Uses  xchacha20poly1305_ietf_decrypt
        /// </summary>
        /// <returns>The decrypt.</returns>
        /// <param name="ciphertext">Ciphertext.</param>
        /// <param name="key">Key.</param>
        /// <param name="nonce">Nonce.</param>
        public override byte[] Decrypt(byte[] ciphertext, byte[] key, byte[] nonce = null)
        {
            byte[] message;
            if (nonce == null)
            {
                nonce      = GetNonce(ciphertext);
                ciphertext = GetCipherText(ciphertext);
            }

            message = new byte[ciphertext.Length];
            long messageLength = ciphertext.Length;

            int result = NativeLibsodium.crypto_aead_xchacha20poly1305_ietf_decrypt(
                message,
                out messageLength,
                null,
                ciphertext,
                ciphertext.Length,
                null, 0,
                nonce,
                key);

            if (result != 0)
            {
                throw new CoflnetException("decryption_error", "Decryption error");
            }

            return(message);
        }
예제 #4
0
    private void Start()
    {
        int x = NativeLibsodium.sodium_init();

        Debug.Log(x);


        const string MESSAGE = "Test message to encrypt";

        byte[] nonce = StreamEncryption.GenerateNonceChaCha20();
        byte[] key   = StreamEncryption.GenerateKey();

        //encrypt it
        byte[] encrypted = StreamEncryption.EncryptChaCha20(MESSAGE, nonce, key);


        //decrypt it
        byte[] decrypted = StreamEncryption.DecryptChaCha20(encrypted, nonce, key);

        string str_origin    = MESSAGE;
        string str_encrypted = Encoding.UTF8.GetString(encrypted);
        string str_decrypted = Encoding.UTF8.GetString(decrypted);

        Debug.Log(str_origin);
        Debug.Log(str_encrypted);
        Debug.Log(str_decrypted);

        txt_origin.text    = str_origin;
        txt_encrypted.text = str_encrypted;
        txt_decrypted.text = str_decrypted;
    }
예제 #5
0
파일: Encrypt.cs 프로젝트: Coflnet/cloud
        public bool DeriveKeysServer()
        {
            if (publicPreKey == null || publicEphemeralKey == null)
            {
                //return false;
                throw new EncryptionKeyIsMissingException();
            }
            // ephermeral And Public Pre Key
            KeyPair ePPK = new KeyPair();

            // ephermeral and Public One Time Key
            KeyPair ePOTK = new KeyPair();

            // own Pre Key and Public Pre Key
            KeyPair oPKPPK = new KeyPair();
            // own Pre Key and Public One Time Key
            KeyPair oPKPOTK = new KeyPair();

            if (oneTimeKeyPair != null)
            {
                NativeLibsodium.crypto_kx_server_session_keys(ePOTK.publicKey, ePOTK.secretKey, oneTimeKeyPair.publicKey, oneTimeKeyPair.secretKey, publicEphemeralKey);
                NativeLibsodium.crypto_kx_server_session_keys(oPKPOTK.publicKey, oPKPOTK.secretKey, oneTimeKeyPair.publicKey, oneTimeKeyPair.secretKey, publicPreKey);
            }
            NativeLibsodium.crypto_kx_server_session_keys(ePPK.publicKey, ePPK.secretKey, ownPreKeyPair.publicKey, ownPreKeyPair.secretKey, publicEphemeralKey);
            NativeLibsodium.crypto_kx_server_session_keys(oPKPPK.publicKey, oPKPPK.secretKey, ownPreKeyPair.publicKey, ownPreKeyPair.secretKey, publicPreKey);

            DeriveSessionKeys(ePPK, oPKPPK, oPKPOTK, ePOTK);
            return(true);
        }
예제 #6
0
 public KeyPair()
 {
     skBytes = new byte[SKEY_LEN];
     vkBytes = new byte[VKEY_LEN];
     NativeLibsodium.crypto_sign_keypair(vkBytes, skBytes);
     Debug.Log($"sk: {Helper.ByteArrayToHexString(skBytes)}, vk: {Helper.ByteArrayToHexString(vkBytes)} ");
     vkString = Helper.ByteArrayToHexString(vkBytes).ToLower();
 }
    public byte[] SignMessage(byte[] hash)
    {
        byte[] buffer       = new byte[hash.Length + 64];
        long   bufferLength = hash.Length + 64;

        NativeLibsodium.crypto_sign(buffer, ref bufferLength, hash, hash.Length, Convert.FromBase64String(ChaChaSigPrivateKey));
        return(buffer);
    }
예제 #8
0
파일: Encrypt.cs 프로젝트: Coflnet/cloud
        /// <summary>
        /// Hashes a given byte array with BLAKE2b (really fast).
        /// </summary>
        /// <returns>The hashed value as byte array</returns>
        /// <param name="message">Message to hash.</param>
        /// <param name="hashLength">Hash length (default 32).</param>
        public static byte[] Hash(byte[] message, int hashLength = 32)
        {
            int messageLength = message.Length;

            byte[] hash = new byte[hashLength];
            NativeLibsodium.crypto_generichash(hash, hashLength, message, messageLength, null, 0);
            return(hash);
        }
예제 #9
0
파일: Encrypt.cs 프로젝트: Coflnet/cloud
        public static byte[] SignByte(byte[] toSign, KeyPair signKeyPair)
        {
            byte[] signed       = new byte[toSign.Length + CRYPTO_SIGN_BYTES];
            long   length       = signed.Length;
            long   toSingLength = toSign.Length;

            NativeLibsodium.crypto_sign(signed, ref length, toSign, toSingLength, signKeyPair.secretKey);
            return(signed);
        }
    public byte[] SignMessage(byte[] hash)
    {
        byte[] buffer       = new byte[100000];
        long   bufferLength = 0;

        NativeLibsodium.crypto_sign(buffer, ref bufferLength, hash, hash.Length, Convert.FromBase64String(encryptionConfig.ChaChaSigPrivateKey));
        Array.Resize(ref buffer, (int)bufferLength);
        return(buffer);
    }
예제 #11
0
        /// <summary>
        /// Signs some bytes.
        /// </summary>
        /// <returns>The singed byte array.</returns>
        /// <param name="toSign">The bytes to sign</param>
        /// <param name="signKeyPair">KeyPair to sign the bytes with.</param>
        public static byte[] SignByteDetached(byte[] toSign, KeyPair signKeyPair)
        {
            byte[] signature       = new byte[CRYPTO_SIGN_BYTES];
            long   signatureLength = signature.Length;
            long   toSingLength    = toSign.Length;

            NativeLibsodium.crypto_sign_detached(signature, ref signatureLength, toSign, toSingLength, signKeyPair.secretKey);
            return(signature);
        }
예제 #12
0
    public byte[] SignOpenMessage(byte[] singed)
    {
        long bufferSize = singed.Length - 64;

        byte[] buffer = new byte[bufferSize];

        NativeLibsodium.crypto_sign_open(buffer, ref bufferSize, singed, singed.Length, ChaChaSigPublicKey);
        return(buffer);
    }
예제 #13
0
    public byte[] SignMessage(byte[] hash)
    {
        long bufferSize = hash.Length + 64;

        byte[] buffer = new byte[bufferSize];

        NativeLibsodium.crypto_sign(buffer, ref bufferSize, hash, hash.Length, ChaChaSigPrivateKey);
        return(buffer);
    }
예제 #14
0
파일: Encrypt.cs 프로젝트: Coflnet/cloud
        public static KeyPair NewSingKeypair()
        {
            KeyPair pair = new KeyPair();

            pair.publicKey = new byte[CRYPTO_SIGN_PUBLICKEYBYTES];
            pair.secretKey = new byte[CRYPTO_SIGN_SECRETKEYBYTES];
            NativeLibsodium.crypto_sign_keypair(pair.publicKey, pair.secretKey);
            return(pair);
        }
    public byte[] SignOpenMessage(byte[] signed)
    {
        byte[] buffer       = new byte[100000];
        long   bufferLength = 0;

        NativeLibsodium.crypto_sign_open(buffer, ref bufferLength, signed, signed.Length, Convert.FromBase64String(encryptionConfig.ChaChaSigPublicKey));
        Array.Resize(ref buffer, (int)bufferLength);
        return(buffer);
    }
    public byte[] SignOpenMessage(byte[] signedVar)
    {
        byte[] value       = new byte[signedVar.Length - 64];
        long   valueLength = value.LongLength;

        NativeLibsodium.crypto_sign_open(value, ref valueLength, signedVar, signedVar.LongLength,
                                         System.Convert.FromBase64String(ChaChaSigPublicKey));
        return(value);
    }
        public byte[] SignMessage(byte[] message)
        {
            long bufferLength = -1;

            NativeLibsodium.crypto_sign(buffer, ref bufferLength, message, message.Length, _privateKey);
            var result = new byte[bufferLength];

            Array.Copy(buffer, result, bufferLength);
            return(result);
        }
예제 #18
0
        /// <inheritdoc/>
        public override SigningKeyPair GenerateKeyPair()
        {
            SigningKeyPair keyPair = new SigningKeyPair(new byte[32],new byte[64]);


            if(NativeLibsodium.crypto_sign_keypair(keyPair.publicKey,keyPair.secretKey) != 0)
                throw new Exception("Could not create new KeyPair");

            keyPair.algorythm = this;
            return keyPair;
        }
예제 #19
0
파일: Encrypt.cs 프로젝트: Coflnet/cloud
        /// <summary>
        /// Generates a new keypair.
        /// </summary>
        /// <returns>The keypair.</returns>
        public static KeyPair NewKeypair()
        {
            byte[] publicKey = new byte[CRYPTO_KX_KEYBYTES];
            byte[] secretKey = new byte[CRYPTO_KX_KEYBYTES];
            NativeLibsodium.crypto_kx_keypair(publicKey, secretKey);
            KeyPair pair = new KeyPair();

            pair.publicKey = publicKey;
            pair.secretKey = secretKey;
            return(pair);
        }
예제 #20
0
        /// <summary>
        /// Derives the keys client for the client.
        /// </summary>
        /// <returns><c>true</c>, if keys client was derived, <c>false</c> otherwise.</returns>
        /// <param name="publicIdentKey">Public identification key.</param>
        /// <param name="publicPreKey">Public pre key.</param>
        /// <param name="signedOneTimeKey">Public one time key.</param>
        public bool DeriveKeysClient(byte[] publicIdentKey, byte[] publicPreKey, byte[] signedOneTimeKey)
        {
            if (publicIdentKey == null)
            {
                throw new EncryptionKeyIsMissingException("Public IdentKey is null");
            }
            if (publicPreKey == null)
            {
                throw new EncryptionKeyIsMissingException("Public PreKey is null");
            }

            this.publicIdentKey = publicIdentKey;
            this.publicPreKey   = publicPreKey;


            ephemeralKeyPair = NewKeypair();

            // ephermeral And Public Pre Key
            KeyPair ePPK = new KeyPair();

            // ephermeral and Public One Time Key
            KeyPair ePOTK = new KeyPair();


            // own Pre Key and Public Pre Key
            KeyPair oPKPPK = new KeyPair();
            // own Pre Key and Public One Time Key
            KeyPair oPKPOTK = new KeyPair();

            // TODO: overgive pre key :)

            //      if (oldKeyPair) {
            //          if (publicOneTimeKey != null) {
            //              NativeLibsodium.crypto_kx_client_session_keys (ePOTK.publicKey, ePOTK.privateKey, ephemeralKeyPair.publicKey, ephemeralKeyPair.privateKey, publicOneTimeKey);
            //              NativeLibsodium.crypto_kx_client_session_keys (oPKPOTK.publicKey, oPKPOTK.privateKey, oldOwnPreKeyPair.publicKey, oldOwnPreKeyPair.privateKey, publicOneTimeKey);
            //          }
            //          NativeLibsodium.crypto_kx_client_session_keys (ePPK.publicKey, ePPK.privateKey, ephemeralKeyPair.publicKey, ephemeralKeyPair.privateKey, publicPreKey);
            //          NativeLibsodium.crypto_kx_client_session_keys (oPKPPK.publicKey, oPKPPK.privateKey, oldOwnPreKeyPair.publicKey, oldOwnPreKeyPair.privateKey, publicPreKey);
            //      } else {
            if (signedOneTimeKey != null)
            {
                // get the onetime key
                publicOneTimeKey = SignByteOpen(signedOneTimeKey, publicPreKey);

                NativeLibsodium.crypto_kx_client_session_keys(ePOTK.publicKey, ePOTK.secretKey, ephemeralKeyPair.publicKey, ephemeralKeyPair.secretKey, publicOneTimeKey);
                NativeLibsodium.crypto_kx_client_session_keys(oPKPOTK.publicKey, oPKPOTK.secretKey, ownPreKeyPair.publicKey, ownPreKeyPair.secretKey, publicOneTimeKey);
            }
            NativeLibsodium.crypto_kx_client_session_keys(ePPK.publicKey, ePPK.secretKey, ephemeralKeyPair.publicKey, ephemeralKeyPair.secretKey, publicPreKey);
            NativeLibsodium.crypto_kx_client_session_keys(oPKPPK.publicKey, oPKPPK.secretKey, ownPreKeyPair.publicKey, ownPreKeyPair.secretKey, publicPreKey);


            DeriveSessionKeys(ePPK, oPKPPK, oPKPOTK, ePOTK);
            return(true);
        }
예제 #21
0
        /// <summary>
        /// Validates a signature with the public part of a KeyPair
        /// </summary>
        /// <returns>The validated byte array or an Exception.</returns>
        /// <param name="signed">Signed byte array.</param>
        /// <param name="publicKey">Public key to validate the signature with.</param>
        public static byte[] SignOpen(byte[] signed, byte[] publicKey)
        {
            byte[] opened  = new byte[signed.Length - CRYPTO_SIGN_BYTES];
            long   length  = signed.Length;
            int    success = NativeLibsodium.crypto_sign_open(opened, ref length, signed, signed.Length, publicKey);

            if (success != 0)
            {
                throw new Exception("Signature is invalid");
            }
            return(opened);
        }
예제 #22
0
        /// <summary>
        /// Validates a signature for given data
        /// </summary>
        /// <returns><c>true</c>, if vertify was successful, <c>false</c> otherwise.</returns>
        /// <param name="signature">Signature.</param>
        /// <param name="data">Data.</param>
        /// <param name="publicKey">Public key.</param>
        public static bool SignVertifyDetached(byte[] signature, byte[] data, byte[] publicKey)
        {
            if (signature == null)
            {
                throw new ArgumentNullException(nameof(signature));
            }

            long length  = data.Length;
            int  success = NativeLibsodium.crypto_sign_verify_detached(signature, data, length, publicKey);

            return(success == 0);
        }
    public byte[] Encrypt(byte[] message, long nonce)
    {
        byte[] buffer = new byte[message.Length];
        int    ret    = NativeLibsodium.crypto_stream_chacha20_xor(buffer, message, message.Length, BitConverter.GetBytes(nonce), Convert.FromBase64String(encryptionConfig.ChaChaEncryptionKey));

        if (ret != 0)
        {
            throw new Exception("Error encrypting message.");
        }

        return(buffer);
    }
예제 #24
0
        public byte[] Decrypt(byte[] message, long nonce)
        {
            byte[] nonceByteArr = BitConverter.GetBytes(nonce);
            byte[] key          = Convert.FromBase64String(ChaChaEncryptionKey);
            byte[] buffer       = new byte[message.Length];
            int    ret          = NativeLibsodium.crypto_stream_chacha20_xor(buffer, message, message.Length, nonceByteArr, key);

            if (ret == 0)
            {
                return(buffer);
            }
            return(null);
        }
    public byte[] Decrypt(byte[] msg, long nonce)
    {
        byte[] nonceBytes = BitConverter.GetBytes(nonce);

        byte[] decrypted = new byte[msg.Length];
        int    ret       = NativeLibsodium.crypto_stream_chacha20_xor(decrypted, msg, msg.Length, nonceBytes, _ChaChaEncryptionKey);

        if (ret != 0)
        {
            throw new Exception("Error derypting message.");
        }

        return(decrypted);
    }
    public byte[] SignOpenMessage(byte[] msg)
    {
        long bufLength = msg.Length - crypto_sign_BYTES;

        byte[] unsignedMsg = new byte[bufLength];

        int rc = NativeLibsodium.crypto_sign_open(unsignedMsg, ref bufLength, msg, msg.Length, _ChaChaSigPublicKey);

        if (rc != 0)
        {
            throw new Exception("Error encrypting message.");
        }

        return(unsignedMsg);
    }
예제 #27
0
        public byte[] SignOpenMessage(byte[] signed)
        {
            byte[] key    = Convert.FromBase64String(ChaChaSigPublicKey);
            byte[] buffer = new byte[signed.Length - 64];

            long bufferLength = 0;

            int ret = NativeLibsodium.crypto_sign_open(buffer, ref bufferLength, signed, signed.Length, key);

            if (ret == 0)
            {
                return(buffer);
            }
            return(null);
        }
예제 #28
0
        public byte[] SignMessage(byte[] hash)
        {
            byte[] key    = Convert.FromBase64String(ChaChaSigPrivateKey);
            byte[] buffer = new byte[hash.Length + 64];

            long bufferLength = 0;

            int ret = NativeLibsodium.crypto_sign(buffer, ref bufferLength, hash, hash.Length, key);

            if (ret == 0)
            {
                return(buffer);
            }
            return(null);
        }
예제 #29
0
파일: Encrypt.cs 프로젝트: Coflnet/cloud
        public static byte[] SignByteOpen(byte[] toValidate, byte[] publicSignKey)
        {
            if (toValidate.Length < CRYPTO_SIGN_BYTES)
            {
                // probably no keys left
                return(null);
            }

            byte[] checkedData      = new byte[toValidate.Length - CRYPTO_SIGN_BYTES];
            long   length           = checkedData.Length;
            long   toValidateLength = toValidate.Length;

            NativeLibsodium.crypto_sign_open(checkedData, ref length, toValidate, toValidateLength, publicSignKey);
            return(checkedData);
        }
    public byte[] SignMessage(byte[] hash)
    {
        byte[] buffer       = new byte[2048];
        long   bufferLength = 2048;

        if (NativeLibsodium.crypto_sign(buffer, ref bufferLength, hash, hash.Length, ChaChaSigPrivateKey) == 0)
        {
            Array.Resize(ref buffer, (int)bufferLength);
            return(buffer);
        }
        else
        {
            Debug.LogError("Incorrect Signature");
            return(null);
        }
    }