Any opinions expressed here are my own and not necessarily those of my employer (I'm self-employed).

Jul 29, 2012

Generating secure Guids

Guids are used extensively throughout Microsoft systems and developers tend to turn to Guid.NewGuid() whenever they need to create a value to uniquely identify something. Guids might also be used as keys or identifiers in security critical operations — under the assumption that they are hard to guess for an attacker. I've been looking around the Internet to see if I could find some guidance on Guid security along with details on how they are generated in the .NET framework. I couldn't find much information, but I did find that Eric Lippert from the C# team recently raised some concerns about the Guids on his blog. So I started digging around to see what more I could find out.

First of all a quick background. Microsoft's Guid is their implementation of the Universally Unique IDentifier (UUID) outlined in RFC 4122. UUIDs are 128 bits, and the Guid class generates version 4 UUIDs, meaning that all bits except those defining the version and variant of the UUID are "random." Please note that 4 bits are used for the version number, and two bits are used for the variant — so it's not a 128 bit random number, it's a 122 bit random number.

I looked into how these Guids are created in the .NET framework. Turns out Guid.NewGuid() simply calls the CoCreateGuid  function on the native ole32.dll, which in turn calls the RPC function UuidCreate. And from its remarks:
The UuidCreate function generates a UUID that cannot be traced to the ethernet address of the computer on which it was generated. It also cannot be associated with other UUIDs created on the same computer. 
Some care has been taken when generating these Guids, but the documentation is far from fullfilling. It's still unclear how easy they are to predict. So, assuming that we cannot trust Guids to be all that "secure", what to do? I've looked around for code that generates a Guid based on the output of a cryptographically strong RNG but couldn't find a good example — so I wrote my own generator that uses the RngCryptoServiceProvider. That way, we know where the bits are coming from. Since it generates proper Guid instances it should be fairly easy to plug it into existing code, e.g. replacing Guid.NewGuid() with SecureGuid.NewGuid(). Also remember to look out for Guids created by constructor: new Guid().

The code

Here's what the code could look like if you wanted to generate a GUID using random bytes from the frameworks's cryptograpically strong RNG. Note the first four bits of the time_hi_and_ver variable is set to version number four, and the first two bits of byte number eight is set according to the variant. Have a look at  RFC 4122  for more details. Apart from that, the code should be straightforward to understand.

using System;
using System.Security.Cryptography;

namespace SecureGuidDemo
    class SecureGuid

        public static Guid NewGuid()
            byte[] bytes = { 0x00, 0x00, 0x00, 0x00,
                               0x00, 0x00, 0x00, 0x00,
                               0x00, 0x00, 0x00, 0x00,
                               0x00, 0x00, 0x00, 0x00 };

            using (var rng = new RNGCryptoServiceProvider())
            var time = BitConverter.ToUInt32(bytes,0);
            var time_mid = BitConverter.ToUInt16(bytes,4);
            var  time_hi_and_ver = BitConverter.ToUInt16(bytes,6);
            time_hi_and_ver = (ushort)((time_hi_and_ver | 0x4000) & 0x4FFF);
            bytes[8] = (byte)((bytes[8] | 0x80) & 0xBF);
            return new Guid(time,time_mid,time_hi_and_ver,

You might look at the code and find it funny that I used the constructor that takes an int, short, short, and byte's. The reason is that I found a bug when creating Guids based on byte arrays. The above code does not trigger the bug, so it should work now and should also work after the bug is fixed (if they decide to do so). I'm in the process of verifying the bug with Microsoft, I'll probably put something up on my blog about it when that's settled.


  1. This is awesome!! really helpful for me. Thanks for sharing with us. Following links also helped me to complete my task.


  2. how can i use this sample for 32 bit GUID

  3. Replies
    1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a .Net developer learn from Dot Net Training in Chennai. or learn thru ASP.NET Essential Training Online . Nowadays Dot Net has tons of job opportunities on various vertical industry.
      or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry.

  4. Get all necessary information about WebWatcher app here.

  5. Very informative, keep posting such good articles, it really helps to know about things.

  6. By reading this article I get a lot of lessons and this is very useful . cara menggugurkan kandungan

  7. It's a great site .. Design looks very good .. Continue to work so!

  8. • Assignments are often considered the burden on the mind of students not giving them ample time for any other activities. Lack of time denies students from performing their beloved hobbies, ceasing them from participating in any sports, cultural affairs. Hence, no overall growth for them. Online Assignment help

  9. Get the best essay writing NZ services from the experts of Students Assignment Help and make your academic life easier. Send us your assignment request at info@studentsassignmenthelp.com or WhatsApp at +44-755-536-9184

  10. Avail the best Australian Assignment Help services in Australia by top rated experts at cheapest prices at Myassignmenthelp.com. MyAssignmenthelp most trusted online assignment writing company provides the assignment writing help service for students in Australia of all levels, starting from high school till Ph.D. Our professional academic assignment helper prepares custom written assignment exclusively for you to achieve A+ grade

  11. Students Assignment Help provides the write my essay NZ services to the students of various universities at a low price. Our highly-experienced writers are available 24x7 for guiding the students for any academic help.

  12. Web Ocean Design is the best IT services provider for complete mobile and web application development. The young development company based in Bihar, India, owned and managed by Vicky who have a good amount of experience in Information Technology, Management and other related fields. We provide technical and creative services ranging from Internet Marketing to Communication maneuver. We are also skilled in website development which includes brand promotion, web designing and software development.

    website design company in patna
    website development company in patna
    website development in patna

    web design company in patna
    web development company in patna
    website design in patna

    website design patna
    seo company in patna
    seo company in bihar

  13. Web Ocean Design is the best IT services provider for complete mobile and web application development. The young development company based in Bihar, India, owned and managed by Vicky who have a good amount of experience in Information Technology, Management and other related fields. We provide technical and creative services ranging from Internet Marketing to Communication maneuver. We are also skilled in website development which includes brand promotion, web designing and software development.

    best seo company in patna
    digital marketing company in patna
    best website design company in patna

    affordable seo service in patna
    website optimization in patna
    educational internet marketing company patna

    social media marketing company patna
    real estate seo company in patna
    ecommerce seo company patna

  14. ac Market is a standout among the best outsider application stores which enable Android clients to ac market download broke applications, hacked diversions and numerous mods of recreations and applications for absolutely free of expense. Air conditioning Market is the best option in contrast to the Google Play Store.

  15. Our assignment help experts could address students' academic topics quite well. Thus, they can opt for our service if they have difficulty in writing the academic task.
    assignment help

  16. My Assignment Services is your first and last destination for every query you have related to ‘assignment help’ because we guarantee you the low-cost possible price of Assignment Writers Australia with the unmatched quality of assignments in Australia.

  17. Loss of time denies college students from appearing their loved hobbies, ceasing them from collaborating in any sports, cultural affairs. Control and other associated fields. We offer Best Dissertation Writing Services UK technical and creative offerings ranging from net advertising to conversation maneuver.

  18. This comment has been removed by the author.

  19. Generating secure Guids is entirely a different stuff for me. Nice presentation. Thanks for sharing. Essay Writing Service

  20. 90minup ข่าวกีฬา ฟุตบอล ผลบอล วิเคราะห์บอล พรีเมียร์ลีก ฟุตบอลไทย

  21. You could also use some other methods connected with some programming languanges like JS or Ruby and try things like here dobryvpn.pl to improve further

  22. TreasureBox is operated by a group of young, passionate, and ambitious people that are working diligently towards the same goal - make your every dollar count, as we believe you deserve something better.
    Check out the best
    bed frames nz
    cheap outdoor furniture nz
    rattan outdoor furniture nz

  23. We provide online assignment help which is not only reliable but comes at a highly affordable price. Students are normally dubious before assignment there finances projects to someone else, as the solution is unknown to them. However, we can assure you that our writers double check the work and never fail to please the clients. Whether you are enroll in under grad, masters or a post grad program, we have writers for all levels and all finance courses.
    For further information & queries, Visit our website finance assignment helper

  24. Hey, very nice site. I came across this on Google, and I am stoked that I did. I will definitely be coming back here more often. Wish I could add to the conversation and bring a bit more to the table, but am just taking in as much info as I can at the moment. Thanks .


  25. Our Pay for custom written college papers services makes your college life bearable and also receive the best assignment writing service fulfilling by enabling you to pass your exams and also in other research and essay writing tasks.

  26. At Assignment studio we have a number of service’s that we have to offer, among them MyAssignmenthelp is one of the most in demand service that majority of the students inquire about.

  27. It is an interesting site where I met a couple of girls after reading this dating.com review. Many people have a profile on the site and I can choose someone who is for me.


Copyright notice

© André N. Klingsheim and www.dotnetnoob.com, 2009-2018. Unauthorized use and/or duplication of this material without express and written permission from this blog’s author and/or owner is strictly prohibited. Excerpts and links may be used, provided that full and clear credit is given to André N. Klingsheim and www.dotnetnoob.com with appropriate and specific direction to the original content.

Read other popular posts