Search code examples
twitteroauthdart

How to make OAuth nonce in Dart


Now, I make OAuth program for twitter in dart.

But, I can't make a oauth_nonce.

First, I think this code.

String create_nonce(){
    var rnd = new Random();
    int i = 0;
    var number = rnd.nextInt(pow(2,8*4));
    List<int> listi = UTF8.encode(number.toString());
    String str = "";
    while(i < 3){
        number = rnd.nextInt(pow(2,8*4)); 
        if(number < pow(2,8*4) - 1){
            number = rnd.nextInt(pow(2,8*4));
       }
       listi = UTF8.encode(number.toString());
       str = str + CryptoUtils.bytesToBase64(listi);
       i++;
    }
    return str;
}

But, this method can't create expected String.

Please tell me how to make a oauth_nonce.

Nonce The oauth_nonce parameter is a unique token your application should generate for each unique request. Twitter will use this value to determine whether a request has been submitted multiple times. The value for this request was generated by base64 encoding 32 bytes of random data, and stripping out all non-word characters, but any approach which produces a relatively random alphanumeric string should be OK here.

oauth_nonce kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg


Solution

  • import 'dart:math' as math;
    import 'package:crypto/crypto.dart';
    
    
    void main() {
      math.Random rnd = new math.Random();
    
      List<int> values = new List<int>.generate(32, (i) => rnd.nextInt(256));
      print(CryptoUtils.bytesToBase64(values));
    }
    

    produces

    QqPlpI8BmDk9byWDqJ4tBCMMIWv24v4WL5KZsufnWqQ=

    I'm not sure what this means exactly

    and stripping out all non-word characters

    I found https://dev.twitter.com/discussions/12445

    You just want to make sure you're not sending characters like "!" "#" or "$" in your oauth_nonce. The process you've suggested sounds like it would work just fine.

    .

    Base64 includes '+' and '/'. You may need to stripping out them since they are non-word characters.

    this should do it

    import 'dart:math' as math;
    import 'package:crypto/crypto.dart';
    
    void main() {
      math.Random rnd = new math.Random();
    
      List<int> values = new List<int>.generate(32, (i) => rnd.nextInt(256));
      print(CryptoUtils.bytesToBase64(values).replaceAll(new RegExp('[=/+]'), ''));
    }
    

    out before and after replaceAll

    elrA+4rWr4O3zNv0L57iOLqTQD94abJ23hFoK+hk6QE=
    elrA4rWr4O3zNv0L57iOLqTQD94abJ23hFoKhk6QE