Search Unity

  1. Unity 2019.2 is now released.
    Dismiss Notice

[Guide] Android Secure Random Bytes

Discussion in 'Android' started by Zocker1996, Nov 20, 2016.

  1. Zocker1996

    Zocker1996

    Joined:
    Jan 12, 2015
    Posts:
    20
    Hi,
    took me a while to figure out how to use java's SecureRandom in Unity.
    I hope this might help someone whos looking for a secure random in Unity Android.


    Code (CSharp):
    1. using UnityEngine;
    2. using System;
    3.  
    4. public class AndroidSecureRandom
    5. {
    6.  
    7.     private static IntPtr SecureRandomPtr, NextBytes;
    8.  
    9.     static AndroidSecureRandom ()
    10.     {
    11.         IntPtr clazz = new AndroidJavaClass ("java.security.SecureRandom").GetRawClass ();
    12.         SecureRandomPtr = AndroidJNI.NewObject (clazz, AndroidJNIHelper.GetConstructorID (clazz), new jvalue[]{ });
    13.         SecureRandomPtr = AndroidJNI.NewGlobalRef (SecureRandomPtr);
    14.         NextBytes = AndroidJNIHelper.GetMethodID (clazz, "nextBytes");
    15.     }
    16.  
    17.     public static byte[] TrueRandom (int count)
    18.     {
    19.             jvalue[] array = new jvalue[]{ new jvalue{ l = AndroidJNI.NewByteArray (count) } };
    20.             AndroidJNI.CallVoidMethod (SecureRandomPtr, NextBytes, array);
    21.             byte[] result = AndroidJNI.FromByteArray (array [0].l);
    22.             AndroidJNI.DeleteLocalRef (array [0].l);
    23.             return result;
    24.     }
    25. }
    Edit:
    So somehow my game crashes if the static constructor isnt invoked from the main thread. I just came up with an other solution, which is also working for ios:

    Code (CSharp):
    1.        
    2. using System.IO;
    3.  
    4. public class SecureRandom {
    5.  public static byte[] TrueRandom (int count)
    6.         {
    7. byte[] result = new byte[count];
    8. #if (UNITY_ANDROID || UNITY_IOS) && !UNITY_EDITOR
    9.             FileStream s = File.OpenRead ("/dev/urandom");
    10.             s.Read (result, 0, count);
    11.             s.Close ();
    12.             return result;
    13. #else
    14. //Only pseudo random here
    15.             for (int i = 0; i < result.Length; i++) {
    16.                 result [i] = (byte)UnityEngine.Random.Range (0, 255);
    17.             }
    18.             return result;
    19. #endif
    20. }
    21. }
    22.  
     
    Last edited: Jan 31, 2017