working on it ...

Filters

Explore Public Snippets

Sort by

Found 1,002 snippets matching: crypto

    public by DavidEGrayson  351133  2  3  0

    Trying to install the cryptography pip in MSYS2 with mingw-w64-x86_64-python2-pip.

    Trying to install the cryptography pip in MSYS2 with mingw-w64-x86_64-python2-pip.: output.txt
    $ pip install -U cryptography
    Collecting cryptography
      Downloading cryptography-1.0.2.tar.gz (332kB)
    Collecting idna>=2.0 (from cryptography)
      Downloading idna-2.0-py2.py3-none-any.whl (61kB)
    Collecting pyasn1>=0.1.8 (from cryptography)
      Downloading pyasn1-0.1.9-py2.py3-none-any.whl
    Collecting six>=1.4.1 (from cryptography)
      Downloading six-1.10.0-py2.py3-none-any.whl
    Collecting setuptools (from cryptography)
      Downloading setuptools-18.4-py2.py3-none-any.whl (462kB)
    Collecting enum34 (from cryptography)
      Downloading enum34-1.0.4.tar.gz
    Collecting ipaddress (from cryptography)
      Downloading ipaddress-1.0.14-py27-none-any.whl
    Collecting cffi>=1.1.0 (from cryptography)
      Downloading cffi-1.2.1.tar.gz (335kB)
    Collecting pycparser (from cffi>=1.1.0->cryptography)
      Downloading pycparser-2.14.tar.gz (223kB)
    Installing collected packages: idna, pyasn1, six, setuptools, enum34, ipaddress, pycparser, cffi, cryptography
      Found existing installation: setuptools 18.3.2
        Uninstalling setuptools-18.3.2:
          Successfully uninstalled setuptools-18.3.2
      Running setup.py install for enum34
        Complete output from command D:/msys64/mingw64/bin/python2.exe -c "import setuptools, tokenize;__file__='c:/users/david/appdata/local/temp/pip-build-ojokdu/enum34/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record c:\users\david\appdata\local\temp/pip-egkxlc-record/install-record.txt --single-version-externally-managed --compile:
        Traceback (most recent call last):
          File "<string>", line 1, in <module>
          File "D:/msys64/mingw64/lib/python2.7/site-packages/setuptools/__init__.py", line 12, in <module>
            from setuptools.extension import Extension
          File "D:/msys64/mingw64/lib/python2.7/site-packages/setuptools/extension.py", line 9, in <module>
            from . import msvc9_support
          File "D:/msys64/mingw64/lib/python2.7/site-packages/setuptools/msvc9_support.py", line 2, in <module>
            import distutils.msvc9compiler
          File "D:/msys64/mingw64/lib/python2.7/distutils/msvc9compiler.py", line 306, in <module>
            raise DistutilsPlatformError("VC %0.1f is not supported by this module" % VERSION)
        distutils.errors.DistutilsPlatformError: VC 6.0 is not supported by this module
    
        ----------------------------------------
    Command "D:/msys64/mingw64/bin/python2.exe -c "import setuptools, tokenize;__file__='c:/users/david/appdata/local/temp/pip-build-ojokdu/enum34/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record c:\users\david\appdata\local\temp/pip-egkxlc-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in c:/users/david/appdata/local/temp/pip-build-ojokdu/enum34
    
    
    

    public by cghersi  290414  1  6  0

    How to simply compute the MD5 hash of a given string, being sure to have the same results retrieved by HASH method of MS SQL Server

    Returns the MD5 hash of the given string
    public static String computeMD5Hash(String input) {
    	if (isNullOrEmpty(input))
    		return "";
    	byte[] bytesOfMessage = null;
    	try {
    		bytesOfMessage = input.getBytes("UTF-16LE");
    	} catch (UnsupportedEncodingException e) {
    		log.error("Cannot support UTF-8 encoding due to " + e, e);
    		return "";
    	}
    	MessageDigest md = null;
    	try {
    		md = MessageDigest.getInstance("MD5");
    	} catch (NoSuchAlgorithmException e) {
    		log.error("Cannot support MD5 algorithm due to " + e, e);
    		return "";
    	}
    	byte[] thedigest = md.digest(bytesOfMessage);
    	return printHexByteArray(thedigest);
    }

    public by micurs  39019  458  10  8

    Using crypto-js in node.js with Typescript

    You can easily install the crypto-js library in node by using the command (on Mac): npm install crypto-js After that you need to download its type definition from Git/DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped/tree/master/cryptojs To make it work, however you need to add the following to the cryptojs.d.ts:
    // add this at the end of crypto.d.ts
      declare module "crypto-js" {
        export = CryptoJS;
      }
    
    // Then you can use the module in typescript
    
    ///<reference path='../types/node.d.ts'/>
    ///<reference path='../types/cryptojs.d.ts'/>
    
    import crypto = require("crypto-js");  
    
    function writeln( msg: string ) {
      process.stdout.write( msg +'\n');
    }
    
    var message : string = "Hello Encrypted World!";
    var cmessage : string = crypto.HmacSHA1( message , "1234").toString();
    writeln( message );
    writeln( cmessage );
    

    public by marksimon232  4615  7  7  8

    Efficient ModExp for Cryptographic purpose in C

    How to implement an efficient routine to calculate the Modular exponentiation as stated in http://en.wikipedia.org/wiki/Modular_exponentiation.
    Using modular multiplication rules:
    i.e. A^2 mod C = (A * A) mod C = ((A mod C) * (A mod C)) mod C
    We can use this to calculate 7^256 mod 13 quickly
    7^1 mod 13 = 7
    7^2 mod 13 = (7^1 *7^1) mod 13 = (7^1 mod 13 * 7^1 mod 13) mod 13
    We can substitute our previous result for 7^1 mod 13 into this equation.
    7^2 mod 13 = (7 *7) mod 13 = 49 mod 13 = 10
    7^2 mod 13 = 10
    7^4 mod 13 = (7^2 *7^2) mod 13 = (7^2 mod 13 * 7^2 mod 13) mod 13
    We can substitute our previous result for 7^2 mod 13 into this equation.
    7^4 mod 13 = (10 * 10) mod 13 = 100 mod 13 = 9
    7^4 mod 13 = 9
    7^8 mod 13 = (7^4 * 7^4) mod 13 = (7^4 mod 13 * 7^4 mod 13) mod 13
    We can substitute our previous result for 7^4 mod 13 into this equation.
    7^8 mod 13 = (9 * 9) mod 13 = 81 mod 13 = 3
    7^8 mod 13 = 3
    We continue in this manner, substituting previous results into our equations.
    ...after 5 iterations we hit:
    7^256 mod 13 = (7^128 * 7^128) mod 13 = (7^128 mod 13 * 7^128 mod 13) mod 13
    7^256 mod 13 = (3 * 3) mod 13 = 9 mod 13 = 9
    7^256 mod 13 = 9
    This has given us a method to calculate A^B mod C quickly provided that B is a power of 2.
    However, we also need a method for fast modular exponentiation when B is not a power of 
    
    Let say.. How can we calculate A^B mod C quickly for any B ?
    => Step 1: Divide B into powers of 2 by writing it in binary
    Start at the rightmost digit, let k=0 and for each digit:
    
    If the digit is 1, we need a part for 2^k, otherwise we do not
    Add 1 to k, and move left to the next digit
    
    => Step 2: Calculate mod C of the powers of two ≤ B
    5^1 mod 19 = 5
    5^2 mod 19 = (5^1 * 5^1) mod 19 = (5^1 mod 19 * 5^1 mod 19) mod 19
    5^2 mod 19 = (5 * 5) mod 19 = 25 mod 19
    5^2 mod 19 = 6
    5^4 mod 19 = (5^2 * 5^2) mod 19 = (5^2 mod 19 * 5^2 mod 19) mod 19
    5^4 mod 19 = (6 * 6) mod 19 = 36 mod 19
    5^4 mod 19 = 17
    5^8 mod 19 = (5^4 * 5^4) mod 19 = (5^4 mod 19 * 5^4 mod 19) mod 19
    5^8 mod 19 = (17 * 17) mod 19 = 289 mod 19
    5^8 mod 19 = 4
    5^16 mod 19 = (5^8 * 5^8) mod 19 = (5^8 mod 19 * 5^8 mod 19) mod 19
    5^16 mod 19 = (4 * 4) mod 19 = 16 mod 19
    5^16 mod 19 = 16
    5^32 mod 19 = (5^16 * 5^16) mod 19 = (5^16 mod 19 * 5^16 mod 19) mod 19
    5^32 mod 19 = (16 * 16) mod 19 = 256 mod 19
    5^32 mod 19 = 9
    5^64 mod 19 = (5^32 * 5^32) mod 19 = (5^32 mod 19 * 5^32 mod 19) mod 19
    5^64 mod 19 = (9 * 9) mod 19 = 81 mod 19
    5^64 mod 19 = 5
    
    => Step 3: Use modular multiplication properties to combine the calculated mod C values
    5^117 mod 19 = ( 5^1 * 5^4 * 5^16 * 5^32 * 5^64) mod 19
    5^117 mod 19 = ( 5^1 mod 19 * 5^4 mod 19 * 5^16 mod 19 * 5^32 mod 19 * 5^64 mod 19) mod 19
    5^117 mod 19 = ( 5 * 17 * 16 * 9 * 5 ) mod 19
    5^117 mod 19 = 61200 mod 19 = 1
    5^117 mod 19 = 1
    
    Notes:
    More optimization techniques exist, but are outside the scope of this snippet. It should be noted that when we perform modular exponentiation in cryptography, it is not unusual to use exponents for B > 1000 bits.
    

    public by DavidEGrayson  1906  0  3  0

    Python cryptography dependencies

    Python cryptography dependencies: py-crypto-deps.md
    [cryptography](https://pypi.python.org/pypi/cryptography)
    - idna >= 2.0
    - pyasn1 >= 0.1.8
    - [six](https://pypi.python.org/pypi/six) >= 1.4.1 - [mingw-packages](https://github.com/Alexpux/MINGW-packages/tree/master/mingw-w64-python-six)
    - [setuptools](https://pypi.python.org/pypi/setuptools) - [mingw-packages](https://github.com/Alexpux/MINGW-packages/tree/master/mingw-w64-python-setuptools)
    - [enum34](https://pypi.python.org/pypi/enum34)
    - ipaddress
    - cffi >= 1.1.0
      - Does not compile cleanly with MSYS2's pip
    
    

    public by Geometry  973  0  4  0

    HmacSha256

    Because Windows.Security.Cryptography.Core.MacAlgorithmNames.HmacSha256 doesn't exist in WP8.1 context we need to do another implementation
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Text;
    using System.Threading.Tasks;
    using Windows.Security.Cryptography;
    using Windows.Security.Cryptography.Core;
    using Windows.Web.Http;
    using Windows.Web.Http.Headers;
    
    // Because Windows.Security.Cryptography.Core.MacAlgorithmNames.HmacSha256 doesn't
    // exist in WP8.1 context we need to do another implementation
    public static string HmacSha256(string key, string value)
    {
        var keyStrm = CryptographicBuffer.ConvertStringToBinary(key, BinaryStringEncoding.Utf8);
        var valueStrm = CryptographicBuffer.ConvertStringToBinary(value, BinaryStringEncoding.Utf8);
    
        var objMacProv = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha256);
        var hash = objMacProv.CreateHash(keyStrm);
        hash.Append(valueStrm);
    
        return CryptographicBuffer.EncodeToBase64String(hash.GetValueAndReset());
    }

    public by msdn  1722  1  7  0

    GenerateAccessToken: Generates a serialized access token using the web token that is passed. Bearer {Header}.{Body}.Thumbprint All the 3 components are Base64 encoded individually. Since a lot of cryptography is performed...

    Generates a serialized access token using the web token that is passed. Bearer {Header}.{Body}.Thumbprint All the 3 components are Base64 encoded individually. Since a lot of cryptography is performed here, this function will be CPU intensive Json Web Security Token Signing certificate. OAuth bearer token (self-signed).
    /// <summary>
    /// Prefix for bearer tokens.
    /// </summary>
    private const string BearerTokenPrefix = "Bearer ";
    
    #region Not for sample app
    
    /// <summary>
    /// Generates a serialized access token using the web token that is passed.
    /// Bearer {Header}.{Body}.Thumbprint
    /// All the 3 components are Base64 encoded individually.
    /// Since a lot of cryptography is performed here, this function will be CPU intensive
    /// </summary>
    /// <param name="webToken">Json Web Security Token</param>
    /// <param name="signingCert">Signing certificate.</param>
    /// <returns>OAuth bearer token (self-signed).</returns>
    public static string GenerateAccessToken(
        JsonWebToken webToken, X509Certificate2 signingCert)
    {
        return String.Format(
            "{0}{1}",
            JWTTokenHelper.BearerTokenPrefix,
            JWTTokenHelper.GenerateAssertion(webToken, signingCert));
    }

    external by cedx  655167  75  4  0

    CRC32 checksum, in C#.

    CRC32 checksum, in C#.: security.cryptography.crc32.cs
    namespace Belin.Security.Cryptography {
      using System;
      using System.Globalization;
      using System.Security.Cryptography;
      
      /// <summary>Computes the CRC32 hash for the input data.</summary>
      [CLSCompliant(false)]
      public class Crc32: HashAlgorithm {
      
        /// <summary>Polynomial used to generate the checksum table.</summary>
        private const uint Polynomial=0xEDB88320;
        
        /// <summary>Seed used to generate the hash code.</summary>
        private const uint Seed=0xFFFFFFFF;
        
        /// <summary>Checksum table of 8-bit encoded values.</summary>
        private static readonly uint[] Table=InitializeTable(Polynomial);
        
        /// <summary>Computed hash code.</summary>
        private uint hash;
        
        /// <summary>Initializes a new instance of the <see cref="Crc32" /> class.</summary>
        public Crc32() {
          this.HashSizeValue=32;
          this.Initialize();
        }
    
        /// <summary>Initializes the instance.</summary>
        public override void Initialize() {
          this.hash=Seed;
        }
    
        /// <summary>Routes data written to the object into the hash algorithm for computing the hash.</summary>
        /// <param name="data">The input to compute the hash code for.</param>
        /// <param name="start">The offset into the byte array from which to begin using data.</param>
        /// <param name="size">The number of bytes in the byte array to use as data.</param>
        protected override void HashCore(byte[] data, int start, int size) {
          this.State=1;
          for(int i=start; i<size; i++) this.hash=(this.hash >> 8) ^ Table[data[i] ^ (this.hash & 0xFF)];
        }
    
        /// <summary>Finalizes the hash computation after the last data is processed by the cryptographic stream object.</summary>
        /// <returns>The computed hash code.</returns>
        protected override byte[] HashFinal() {
          this.HashValue=BitConverter.GetBytes(~this.hash);
          this.State=0;
          return this.HashValue;
        }
        
        /// <summary>Converts a byte array to a hexadecimal string.</summary>
        /// <param name="data">Data to convert.</param>
        /// <returns>Hexadecimal string corresponding to the specified data.</returns>
        public static string ToHex(byte[] data) {
          var builder=new StringBuilder();
          foreach(var item in data) builder.Append(item.ToString("x2", CultureInfo.InvariantCulture));
          return builder.ToString();
        }
    
        /// <summary>Converts a byte array to unsigned 32-bit integer.</summary>
        /// <remarks>The array passed as a parameter must have a maximum length of 4 elements.<remarks>
        /// <param name="data">Data to convert.</param>
        /// <returns>Unsigned 32-bit integer corresponding to the specified data.</returns>
        public static uint ToUInt32(byte[] data){
          return uint.Parse(ToHex(data), NumberStyles.HexNumber);
        }
    
        /// <summary>Initializes the checksum table from the specified polynomial.</summary>
        /// <param name="polynomial">Polynomial used to generate the checksum table.</param>
        /// <returns>Checksum table of 8-bit encoded values.</returns>
        private static uint[] InitializeTable(uint polynomial) {
          var table=new uint[256];
          
          for(int i=0; i<table.Length; i++) {
            var value=(uint) i;
            
            for(int j=0; j<8; j++) {
              if((value & 1)==1) value=(value>>1)^polynomial;
              else value>>=1;
            }
            
            table[i]=value;
          }
          
          return table;
        }
      }
    }
    
    
    

    external by Minh Triet Pham Tran  228  0  3  0

    Apache Crypto Configuration

    Apache Crypto Configuration: gistfile1.txt
    SSLCipherSuite EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH
    SSLProtocol All -SSLv2 -SSLv3
    SSLHonorCipherOrder On
    Header always set Strict-Transport-Security "max-age=63072000; includeSubdomains; preload"
    Header always set X-Frame-Options DENY
    Header always set X-Content-Type-Options nosniff
    # Requires Apache >= 2.4
    SSLCompression off 
    SSLSessionTickets Off
    SSLUseStapling on 
    SSLStaplingCache "shmcb:logs/stapling-cache(150000)"
    
    

    external by Github  360  0  3  0

    The Matasano Crypto Challenges Set 1 (http://cryptopals.com/sets/1)

    The Matasano Crypto Challenges Set 1 (http://cryptopals.com/sets/1): Set1.hs
    module Set1 where
    
    import qualified Data.Map.Strict as M
    import Data.Bits
    import Data.Word
    import Data.Char (toLower)
    import qualified Data.ByteString as BS
    import qualified Data.ByteString.Char8 as C
    
    -- Helpers
    stringToBytes :: String -> [Word8]
    stringToBytes = BS.unpack . C.pack
    
    charToBytes :: Char -> [Word8]
    charToBytes = BS.unpack . C.singleton
    
    bytesToString :: [Word8] -> String
    bytesToString = C.unpack . BS.pack
    
    -- Set 1, Challenge 1: Base64 encoding -----------------------------------------
    base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
    base64Dict = M.fromList $ zip [0..] base64Chars
    getBase64Char b = M.findWithDefault ' ' b base64Dict
    
    encodeTriple :: Word8 -> Word8 -> Word8 -> String
    encodeTriple a b c =
      map getBase64Char $ zipWith (.|.)
        (map transform [(a, -2, 0x3f), (a,  4, 0x30), (b,  2, 0x3c), (c, 0, 0x3f)])
        (map transform [(0,  0,    0), (b, -4, 0x0f), (c, -6, 0x03), (0, 0,    0)])
      where
        transform (a, s, m) = a `shift` s .&. m
    
    bytesToBase64 :: [Word8] -> String
    bytesToBase64 [] = []
    bytesToBase64 [a] = take 2 (encodeTriple a 0 0) ++ "=="
    bytesToBase64 [a, b] = take 3 (encodeTriple a b 0) ++ "="
    bytesToBase64 (a:b:c:xs) = encodeTriple a b c ++ bytesToBase64 xs
    
    stringToBase64 :: String -> String
    stringToBase64 = bytesToBase64 . stringToBytes
    
    -- Set 1, Challenge 2: hex string conversion -----------------------------------
    hexChars = "0123456789abcdef"
    hexDict = M.fromList $ zip hexChars [0..]
    hexToByte c = M.findWithDefault 0 (toLower c) hexDict
    
    hexRevDict = M.fromList $ zip [0..] hexChars
    byteToHex b = M.findWithDefault ' ' b hexRevDict
    
    hexStringToBytes :: String -> [Word8]
    hexStringToBytes [] = []
    hexStringToBytes [a] = [0]
    hexStringToBytes (a:b:xs) = 16 * hexToByte a + hexToByte b : hexStringToBytes xs
    
    bytesToHexString :: [Word8] -> String
    bytesToHexString [] = []
    bytesToHexString (x:xs) = byteToHex (x `shiftR` 4 .&. 0xf) : byteToHex (x .&. 0xf) : bytesToHexString xs
    
    hexStringToBase64 :: String -> String
    hexStringToBase64 = bytesToBase64 . hexStringToBytes
    
    -- Set 1, Challenge 3: Decrypt single-byte XOR with frequency analysis ---------
    fixedXor :: [Word8] -> [Word8] -> [Word8]
    fixedXor = zipWith xor
    
    fixedXorHexStr :: String -> String -> String
    fixedXorHexStr a b = bytesToHexString $ fixedXor (hexStringToBytes a) (hexStringToBytes b)
    
    -- Decrypt a hex-encoded message with a single-byte XOR
    singleXorHexStr s c = bytesToString $ fixedXor (hexStringToBytes s) $ cycle (charToBytes c)
    
    -- English letter frequencies (https://en.wikipedia.org/wiki/Letter_frequency)
    charFreqEnglish = M.fromList
      [ ('a', 0.08167)
      , ('b', 0.01492)
      , ('c', 0.02782)
      , ('d', 0.04253)
      , ('e', 0.1270)
      , ('f', 0.02228)
      , ('g', 0.02015)
      , ('h', 0.06094)
      , ('i', 0.06966)
      , ('j', 0.00153)
      , ('k', 0.00772)
      , ('l', 0.04025)
      , ('m', 0.02406)
      , ('n', 0.06749)
      , ('o', 0.07507)
      , ('p', 0.01929)
      , ('q', 0.00095)
      , ('r', 0.05987)
      , ('s', 0.06327)
      , ('t', 0.09056)
      , ('u', 0.02758)
      , ('v', 0.00978)
      , ('w', 0.02361)
      , ('x', 0.00150)
      , ('y', 0.01974)
      , ('z', 0.00074) ]
    
    freqExpected c = M.findWithDefault 0 c charFreqEnglish
    
    -- number of occurences of an element in a list
    count :: Eq a => a -> [a] -> Int
    count c = length . filter (==c)
    
    -- frequency of an element in a list
    freq :: Eq a => [a] -> a -> Double
    freq s c = fromIntegral (count c s) / fromIntegral (length s)
    
    -- score for a Char = square deviation from expected frequency
    getScore :: String -> Char -> Double
    getScore s c = (freq s c - freqExpected c) ^^ 2
    
    -- score an entire string (sum scores for 'a'..'z' and unexpected characters '*')
    scoreString :: String -> Double
    scoreString s = sum $ map (getScore s') ('*':['a'..'z'])
      where
        s' = map (replaceNonAlpha . toLower) s
        replaceNonAlpha c = if c `elem` ['a'..'z'] then c else '*'
    
    -- Decrypt with every letter, calculate score, and return the result with the lowest score
    tryDecryptHex :: String -> String
    tryDecryptHex s = snd . minimum $ map ((\s -> (scoreString s, s)) . singleXorHexStr s) ['A'..'Z']
    
    
    
    • Public Snippets
    • Channels Snippets