USP_ADD_TABLE_MAC

Parameters

Parameter Parameter Type Mode Description
@TABLENAME nvarchar(128) IN

Definition

Copy

                create procedure [dbo].[USP_ADD_TABLE_MAC]
                (
                    @TABLENAME sysname
                )
                with execute as owner
                as
                    set nocount on;

                    declare @TABLEID int;
                    declare @KEY varbinary(100);
                    declare @KEYGUID uniqueidentifier;
                    declare @MSG nvarchar(max);

                    select @TABLEID = object_id(@TABLENAME);

                    if @TABLEID is null
                        begin
                            set @MSG = 'Could not locate ' + @TABLENAME + ' table.';
                            raiserror(@MSG, 16, 1);
                            return 1;
                        end

                    select 
                        @KEY = MSGAUTHCODE
                    from
                        dbo.MACINDEXKEY
                    where
                        ID = @TABLEID;

                    if @KEY is not null
                        begin
                            set @MSG = 'A key has already been defined for the ' + @TABLENAME + ' table.';
                            raiserror(@MSG, 16, 1);
                            return 1;
                        end

                    set @KEYGUID = key_guid('sym_BBInfinity');

                    -- Open the encryption key (make sure to close the master key before doing
                    -- any operation that may end the module; otherwise the key will remain
                    -- open after the stored procedure finishes execution)

                    open symmetric key sym_BBInfinity decryption by asymmetric key asym_BBInfinity;

                    -- The new MAC key is derived from an encryption of a newly created GUID. 
                    -- Since the encryption function is not deterministic, the output is random.
                    -- After getting this cipher, we calculate a SHA1 Hash for it.
                    select @KEY = hashbytes( N'SHA1', encryptbykey(@KEYGUID, convert(varbinary(100), newid())));

                    -- Protect the new MAC key
                    set @KEY = encryptbykey(@KEYGUID, @KEY);

                    close symmetric key sym_BBInfinity;

                    -- Since we have closed the key we opened, it is safe to return from the SP at any time.

                    if @KEY is null
                        begin
                            set @MSG = 'Unable to create MAC key for ' + @TABLENAME + ' table.';
                            raiserror(@MSG, 16, 1);
                            return 1;
                        end

                    insert into dbo.MACINDEXKEY(ID, MSGAUTHCODE) values (@TABLEID, @KEY);

                    return 0;