如何在Dart中使OAuth随机数

sh4*_*869 2 twitter oauth dart

现在,我用飞镖制作Twitter的OAuth程序。

但是,我无法发出oauth_nonce。

首先,我认为这段代码。

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;
}
Run Code Online (Sandbox Code Playgroud)

但是,此方法无法创建预期的字符串。

请告诉我如何制作oauth_nonce。

Nonce oauth_nonce参数是您的应用程序应为每个唯一请求生成的唯一令牌。Twitter将使用此值来确定请求是否已多次提交。该请求的值是通过base64编码32个字节的随机数据并去除所有非单词字符而生成的,但是任何产生相对随机的字母数字字符串的方法都可以在这里使用。

oauth_nonce kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg

Gün*_*uer 5

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));
}
Run Code Online (Sandbox Code Playgroud)

产生

QqPlpI8BmDk9byWDqJ4tBCMMIWv24v4WL5KZsufnWqQ =

我不确定这到底意味着什么

并去除所有非单词字符

我找到了https://dev.twitter.com/discussions/12445

您只想确保您没有发送“!”之类的字符。您的oauth_nonce中的“#”或“ $”。您建议的过程听起来不错。

Base64包含“ +”和“ /”。您可能需要删除它们,因为它们是非单词字符。

这应该做

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('[=/+]'), ''));
}
Run Code Online (Sandbox Code Playgroud)

之前和之后 replaceAll

elrA + 4rWr4O3zNv0L57iOLqTQD94abJ23hFoK + hk6QE =
elrA4rWr4O3zNv0L57iOLqTQD94abJ23hFoKhk6QE

  • `CryptoUtils.bytesToBase64` 现已弃用,应替换为 `dart:convert` 包中的 `base64UrlEncode` =&gt; `import 'dart:convert';` (2认同)