Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SHA1 hashing in SQLite: how?

Working with several DBs in parallel and need to initialize some records with hashed passwords. In MS SQL server there are handy functions that allow to hash on the fly:


HashBytes('SHA1', CONVERT(nvarchar(32), N'admin'))

Is there is a similar function with SQLite?

If not, which is the easiest workaround (such as select from SQL server and somehow insert it into SQLite tables)?

The preferred hashing algorithm is SHA1 and the passwords are stored in a BLOB column.

Update: I use C# language in the current project.

like image 891
BreakPhreak Avatar asked Jul 05 '10 11:07

BreakPhreak


4 Answers

There is no such function built into SQLite3.

But you could define a user function e.g. with sqlite3_create_function if you're using the C interface, and implement SHA-1 with that. (But if you're having a programmable interface perhaps you could just SHA-1 the password outside of the SQL engine.)

You could also try to find / create an extension and load with the load_extension function, but I don't have experience on that.

Edit:

  • See this answer on SQLiteFunction Simple Not Working for how to define a custom function with System.Data.SQLite in C#.
  • Use System.Security.Cryptography.SHA1 to compute the SHA-1 hash.
like image 99
kennytm Avatar answered Nov 17 '22 10:11

kennytm


SQLite does not come with SHA1, but it is relatively easily to add. You didn't say what language, you're using, but you can look at the C documentation for create_function and sqlite3_result. You can also take a look at this example of how to add SHA1 to SQLite using Ruby.

With System.Data.SQLite, they're called user-defined functions. You can look at this example on the main site.

like image 25
Matthew Flaschen Avatar answered Nov 17 '22 10:11

Matthew Flaschen


Noting that sqlite does have a sha1() extension added in 2017

https://www.sqlite.org/src/file/ext/misc/sha1.c

although it may not be enabled by default.

like image 35
tomc Avatar answered Nov 17 '22 09:11

tomc


You can create a custom function for SHA1 in C# like this:

[SQLiteFunction(Name = "Sha1", Arguments = 1, FuncType = FunctionType.Scalar)]
public class Sha1 : SQLiteFunction
{
    public override object Invoke(object[] args)
    {
        var buffer = args[0] as byte[];

        if ( buffer == null )
        {
            var s = args[0] as string;

            if ( s != null )
                buffer = Encoding.Unicode.GetBytes(s);
        }

        if ( buffer == null )
            return null;

        using ( var sha1 = SHA1.Create() )
        {
            return sha1.ComputeHash(buffer);
        }
    }
}

This function can be called for binary data or strings. Strings are hashed in their Unicode representation. This should match SQL Server.

The function can be called like this:

select sha1('abc')
select sha1(x'010203')
like image 4
Jörg Avatar answered Nov 17 '22 09:11

Jörg