GooglePrettify

2019年5月23日 星期四

Decrypting with private key from .pem file in c# with .NET crypto library

//------- Parses binary ans.1 RSA private key; returns RSACryptoServiceProvider  ---
public static RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey)
{
    byte[] MODULUS, E, D, P, Q, DP, DQ, IQ ;

// ---------  Set up stream to decode the asn.1 encoded RSA private key  ------
    MemoryStream  mem = new MemoryStream(privkey) ;
    BinaryReader binr = new BinaryReader(mem) ;    //wrap Memory Stream with BinaryReader for easy reading
    byte bt = 0;
    ushort twobytes = 0;
    int elems = 0;
    try {
        twobytes = binr.ReadUInt16();
        if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
            binr.ReadByte();    //advance 1 byte
        else if (twobytes == 0x8230)
            binr.ReadInt16();   //advance 2 bytes
        else
            return null;

        twobytes = binr.ReadUInt16();
        if (twobytes != 0x0102) //version number
            return null;
        bt = binr.ReadByte();
        if (bt !=0x00)
            return null;


//------  all private key components are Integer sequences ----
        elems = GetIntegerSize(binr);
        MODULUS = binr.ReadBytes(elems);

        elems = GetIntegerSize(binr);
        E = binr.ReadBytes(elems) ;

        elems = GetIntegerSize(binr);
        D = binr.ReadBytes(elems) ;

        elems = GetIntegerSize(binr);
        P = binr.ReadBytes(elems) ;

        elems = GetIntegerSize(binr);
        Q = binr.ReadBytes(elems) ;

        elems = GetIntegerSize(binr);
        DP = binr.ReadBytes(elems) ;

        elems = GetIntegerSize(binr);
        DQ = binr.ReadBytes(elems) ;

        elems = GetIntegerSize(binr);
        IQ = binr.ReadBytes(elems) ;

        Console.WriteLine("showing components ..");
        if (verbose) {
            showBytes("\nModulus", MODULUS) ;
            showBytes("\nExponent", E);
            showBytes("\nD", D);
            showBytes("\nP", P);
            showBytes("\nQ", Q);
            showBytes("\nDP", DP);
            showBytes("\nDQ", DQ);
            showBytes("\nIQ", IQ);
        }

// ------- create RSACryptoServiceProvider instance and initialize with public key -----
        RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
        RSAParameters RSAparams = new RSAParameters();
        RSAparams.Modulus =MODULUS;
        RSAparams.Exponent = E;
        RSAparams.D = D;
        RSAparams.P = P;
        RSAparams.Q = Q;
        RSAparams.DP = DP;
        RSAparams.DQ = DQ;
        RSAparams.InverseQ = IQ;
        RSA.ImportParameters(RSAparams);
        return RSA;
    }
    catch (Exception) {
        return null;
    }
    finally {
        binr.Close();
    }
}

from : https://stackoverflow.com/questions/1162504/decrypting-with-private-key-from-pem-file-in-c-sharp-with-net-crypto-library

How can I generate random alphanumeric strings?

private static Random random = new Random();
public static string RandomString(int length)
{
    const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    return new string(Enumerable.Repeat(chars, length)
      .Select(s => s[random.Next(s.Length)]).ToArray());
}

from : https://stackoverflow.com/questions/1344221/how-can-i-generate-random-alphanumeric-strings

2019年4月17日 星期三

MSSQL convert int timestamp to datetime

CREATE FUNCTION dbo.fn_ToDT (@Datetime BIGINT)
RETURNS DATETIME
AS
BEGIN
    DECLARE @result datetime = Convert(datetime, '01/01/1970');

    DECLARE @LocalTimeOffset BIGINT
           ,@AdjustedLocalDatetime BIGINT
           ,@MinIntValue INT
           ,@MaxIntValue INT
           ,@RemainingSeconds BIGINT;

    -- define int limit
    SET @MinIntValue = -2147483648;
    SET @MaxIntValue = 2147483647;

    -- compute the datetime with the offset
    SET @LocalTimeOffset = DATEDIFF(second,GETDATE(),GETUTCDATE())
    SET @AdjustedLocalDatetime = @Datetime - @LocalTimeOffset

    -- going to the future
    WHILE(@AdjustedLocalDatetime>@MaxIntValue)
    BEGIN
        SET @AdjustedLocalDatetime = @AdjustedLocalDatetime - @MaxIntValue;
        SELECT @result = Convert(datetime, dateadd(ss, @MaxIntValue,@result));
    END

    -- going back in the past
    WHILE(@AdjustedLocalDatetime<@MinIntValue)
    BEGIN
        SET @AdjustedLocalDatetime = @AdjustedLocalDatetime - @MinIntValue;
        SELECT @result = Convert(datetime, dateadd(ss, @MinIntValue,@result));
    END

    RETURN (SELECT DATEADD(second,@AdjustedLocalDatetime, @result))
END;

Usage:
dbo.fn_ToDT([LastUpdateTime]) as [LastUpdateTime]

2019年2月18日 星期一

MS-SQL 分頁 (SQL Paging)

MS-SQL 的分頁語法一直是很多程式人員的痛,但是微軟也不是沒有改進

在 SQL2005 的時候,推出了  ROW_NUMBER() 函數,讓程式人員寫分頁語法的時候負擔小了一點

現在 SQL 的分頁語法終於有比較快速的方法了.............
如果我要抓 第20筆到 30 筆的資料可以用下面的語法

SELECT * FROM Orders
ORDER BY OrderID
OFFSET 20 ROWS
FETCH NEXT 10 ROWS ONLY;
還沒說完,請繼續往下看~~


很可惜的是上面的語法僅支援 SQL2011、SQL Server CE4.0,真是殘念>"<

所以還是乖乖的用 CTE 加上 ROW_NUMBER() 的方式來做

;
WITH CTEResults AS 
(
     SELECT
         IDColumn
,
         SomeField
,
         DateField ROW_NUMBER
() OVER (ORDER BY DateField) AS RowNum
    
FROM MyTable ) 
SELECT
 *,
(SELECT MAX(RowNum) FROM CTEResults)  
as TotalRows  ---### 這裡會回傳總筆數 FROM CTEResults WHERE RowNum BETWEEN 20 AND 30;

from : https://blog.xuite.net/dlnk/work/51786477-MS-SQL+%E5%88%86%E9%A0%81+%28SQL+Paging%29

2019年2月17日 星期日

MSSQL Performance tuning statement

SET STATISTICS IO ON;
SET STATISTICS TIME ON;

DBCC FreeProcCache
DBCC DropCleanBuffers

Select *
FROM users
WHERE DisplayName='xxx'

2019年2月13日 星期三

MSSQL TRY CATCH

BEGIN TRANSACTION
BEGIN TRY
    INSERT news_group (newsid, groupid)
    VALUES (99, 99)
   
    COMMIT TRANSACTION
END TRY
BEGIN CATCH
    SELECT ERROR_NUMBER() AS ErrNo, ERROR_MESSAGE() AS ErrMsg
    ROLLBACK TRANSACTION
END CATCH

MSSQL COALESCE

DECLARE @items AS VARCHAR(MAX)

SELECT @items = COALESCE(@items + ',', '') + item_text
FROM vote_items WHERE voteid = 10

SELECT @items