如何从Flutter中的RSA私钥生成令牌?

时间:2020-08-24 09:21:04

标签: java flutter dart jwt

大家好,我对很多事情感到非常困惑。我所知道的是,我必须在一天结束时生成令牌。我得到了一些RSA私钥,即“ XYZ ......”。 ............ dsdsfm”((显然由于安全问题,我无法透露它),从那里我必须生成一些令牌,这些令牌将用作API http请求授权的标头。

问题是JsonWebKey的这些与Internet相关的东西以及我所不具备的所有东西,但我仍然尝试学习它们,但不是很清楚。我试图实现某些人用Java编写的代码(并且家伙只懂Java而不会懂)。

对于Flutter的实现,我在pub.dev中尝试了两个插件...但是我没有得到正确的输出。

第一个是https://pub.dev/packages/jose>I尝试了与示例页面类似的内容,如下所示:

import 'dart:convert';
import 'dart:io';

import 'package:crypto_keys/crypto_keys.dart';
import 'package:jose/jose.dart';
import 'package:x509/x509.dart';

String pkey="XXXXXXXXXXXXXsfds";

void keyGenerator() async {
 //await example1();
  await example2();
//  await example3();
//  await example4();
//  await example5();
 // await example6();
//  await example7();
//  await example8();
}

// decode and verify a JWS
void example1() async {
  var encoded = pkey;

  // create a JsonWebSignature from the encoded string
  var jws = JsonWebSignature.fromCompactSerialization(encoded);

  // extract the payload
  var payload = jws.unverifiedPayload;

  print('content of jws: ${payload.stringContent}');
  print('protected parameters: ${payload.protectedHeader.toJson()}');

  // create a JsonWebKey for verifying the signature
  var jwk = JsonWebKey.fromJson({
    'kty': 'RSA',
    'alg': 'RS256',

  });
  var keyStore = JsonWebKeyStore()..addKey(jwk);

  // verify the signature
  var verified = await jws.verify(keyStore);
  print('signature verified: $verified');
}

// create a JWS
void example2() async {
  // create a builder
  var builder = JsonWebSignatureBuilder();

  // set the content
  builder.stringContent = 'It is me';

  // set some protected header
  builder.setProtectedHeader('createdAt', DateTime.now().toIso8601String());

  // add a key to sign, you can add multiple keys for different recipients
  builder.addRecipient(
      JsonWebKey.fromJson({
        'kty': 'RSA',
        'kid': pkey,
      }),
      algorithm: 'RS256');

  // build the jws
  var jws = builder.build();

  // output the compact serialization
  print('jws compact serialization: ${jws.toCompactSerialization()}');

  // output the json serialization
  print('jws json serialization: ${jws.toJson()}');
}

// decode and decrypt a JWE
void example3() async {
  var encoded = 'eyJhbGciOiJSU0ExXzUiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0.'
      'UGhIOguC7IuEvf_NPVaXsGMoLOmwvc1GyqlIKOK1nN94nHPoltGRhWhw7Zx0-kFm'
      '1NJn8LE9XShH59_i8J0PH5ZZyNfGy2xGdULU7sHNF6Gp2vPLgNZ__deLKxGHZ7Pc'
      'HALUzoOegEI-8E66jX2E4zyJKx-YxzZIItRzC5hlRirb6Y5Cl_p-ko3YvkkysZIF'
      'NPccxRU7qve1WYPxqbb2Yw8kZqa2rMWI5ng8OtvzlV7elprCbuPhcCdZ6XDP0_F8'
      'rkXds2vE4X-ncOIM8hAYHHi29NX0mcKiRaD0-D-ljQTP-cFPgwCp6X-nZZd9OHBv'
      '-B3oWh2TbqmScqXMR4gp_A.'
      'AxY8DCtDaGlsbGljb3RoZQ.'
      'KDlTtXchhZTGufMYmOYGS4HffxPSUrfmqCHXaI9wOGY.'
      '9hH0vgRfYgPnAHOd8stkvw';

  // create a JsonWebEncryption from the encoded string
  var jwe = JsonWebEncryption.fromCompactSerialization(encoded);

  // create a JsonWebKey for decrypting the signature
  var jwk = JsonWebKey.fromJson(
    {
      'kty': 'RSA',
      'n': 'sXchDaQebHnPiGvyDOAT4saGEUetSyo9MKLOoWFsueri23bOdgWp4Dy1Wl'
          'UzewbgBHod5pcM9H95GQRV3JDXboIRROSBigeC5yjU1hGzHHyXss8UDpre'
          'cbAYxknTcQkhslANGRUZmdTOQ5qTRsLAt6BTYuyvVRdhS8exSZEy_c4gs_'
          '7svlJJQ4H9_NxsiIoLwAEk7-Q3UXERGYw_75IDrGA84-lA_-Ct4eTlXHBI'
          'Y2EaV7t7LjJaynVJCpkv4LKjTTAumiGUIuQhrNhZLuF_RJLqHpM2kgWFLU'
          '7-VTdL1VbC2tejvcI2BlMkEpk1BzBZI0KQB0GaDWFLN-aEAw3vRw',
      'e': 'AQAB',
      'd': 'VFCWOqXr8nvZNyaaJLXdnNPXZKRaWCjkU5Q2egQQpTBMwhprMzWzpR8Sxq'
          '1OPThh_J6MUD8Z35wky9b8eEO0pwNS8xlh1lOFRRBoNqDIKVOku0aZb-ry'
          'nq8cxjDTLZQ6Fz7jSjR1Klop-YKaUHc9GsEofQqYruPhzSA-QgajZGPbE_'
          '0ZaVDJHfyd7UUBUKunFMScbflYAAOYJqVIVwaYR5zWEEceUjNnTNo_CVSj'
          '-VvXLO5VZfCUAVLgW4dpf1SrtZjSt34YLsRarSb127reG_DUwg9Ch-Kyvj'
          'T1SkHgUWRVGcyly7uvVGRSDwsXypdrNinPA4jlhoNdizK2zF2CWQ',
      'p': '9gY2w6I6S6L0juEKsbeDAwpd9WMfgqFoeA9vEyEUuk4kLwBKcoe1x4HG68'
          'ik918hdDSE9vDQSccA3xXHOAFOPJ8R9EeIAbTi1VwBYnbTp87X-xcPWlEP'
          'krdoUKW60tgs1aNd_Nnc9LEVVPMS390zbFxt8TN_biaBgelNgbC95sM',
      'q': 'uKlCKvKv_ZJMVcdIs5vVSU_6cPtYI1ljWytExV_skstvRSNi9r66jdd9-y'
          'BhVfuG4shsp2j7rGnIio901RBeHo6TPKWVVykPu1iYhQXw1jIABfw-MVsN'
          '-3bQ76WLdt2SDxsHs7q7zPyUyHXmps7ycZ5c72wGkUwNOjYelmkiNS0',
      'dp': 'w0kZbV63cVRvVX6yk3C8cMxo2qCM4Y8nsq1lmMSYhG4EcL6FWbX5h9yuv'
          'ngs4iLEFk6eALoUS4vIWEwcL4txw9LsWH_zKI-hwoReoP77cOdSL4AVcra'
          'Hawlkpyd2TWjE5evgbhWtOxnZee3cXJBkAi64Ik6jZxbvk-RR3pEhnCs',
      'dq': 'o_8V14SezckO6CNLKs_btPdFiO9_kC1DsuUTd2LAfIIVeMZ7jn1Gus_Ff'
          '7B7IVx3p5KuBGOVF8L-qifLb6nQnLysgHDh132NDioZkhH7mI7hPG-PYE_'
          'odApKdnqECHWw0J-F0JWnUd6D2B_1TvF9mXA2Qx-iGYn8OVV1Bsmp6qU',
      'qi': 'eNho5yRBEBxhGBtQRww9QirZsB66TrfFReG_CcteI1aCneT0ELGhYlRlC'
          'tUkTRclIfuEPmNsNDPbLoLqqCVznFbvdB7x-Tl-m0l_eFTj2KiqwGqE9PZ'
          'B9nNTwMVvH3VRRSLWACvPnSiwP8N5Usy-WRXS-V7TbpxIhvepTfE0NNo'
    },
  );
  var keyStore = JsonWebKeyStore()..addKey(jwk);

  // decrypt the payload
  var payload = await jwe.getPayload(keyStore);
  print('decrypted content: ${payload.stringContent}');
}

// create a JWE
void example4() async {
  // create a builder
  var builder = JsonWebEncryptionBuilder();

  // set the content
  builder.stringContent = 'This is my bigest secret';

  // set some protected header
  builder.setProtectedHeader('createdAt', DateTime.now().toIso8601String());

  // add a key to encrypt the Content Encryption Key
  var jwk = JsonWebKey.fromJson(
    {
      'kty': 'RSA',
      'n': 'sXchDaQebHnPiGvyDOAT4saGEUetSyo9MKLOoWFsueri23bOdgWp4Dy1Wl'
          'UzewbgBHod5pcM9H95GQRV3JDXboIRROSBigeC5yjU1hGzHHyXss8UDpre'
          'cbAYxknTcQkhslANGRUZmdTOQ5qTRsLAt6BTYuyvVRdhS8exSZEy_c4gs_'
          '7svlJJQ4H9_NxsiIoLwAEk7-Q3UXERGYw_75IDrGA84-lA_-Ct4eTlXHBI'
          'Y2EaV7t7LjJaynVJCpkv4LKjTTAumiGUIuQhrNhZLuF_RJLqHpM2kgWFLU'
          '7-VTdL1VbC2tejvcI2BlMkEpk1BzBZI0KQB0GaDWFLN-aEAw3vRw',
      'e': 'AQAB',
      'd': 'VFCWOqXr8nvZNyaaJLXdnNPXZKRaWCjkU5Q2egQQpTBMwhprMzWzpR8Sxq'
          '1OPThh_J6MUD8Z35wky9b8eEO0pwNS8xlh1lOFRRBoNqDIKVOku0aZb-ry'
          'nq8cxjDTLZQ6Fz7jSjR1Klop-YKaUHc9GsEofQqYruPhzSA-QgajZGPbE_'
          '0ZaVDJHfyd7UUBUKunFMScbflYAAOYJqVIVwaYR5zWEEceUjNnTNo_CVSj'
          '-VvXLO5VZfCUAVLgW4dpf1SrtZjSt34YLsRarSb127reG_DUwg9Ch-Kyvj'
          'T1SkHgUWRVGcyly7uvVGRSDwsXypdrNinPA4jlhoNdizK2zF2CWQ',
      'p': '9gY2w6I6S6L0juEKsbeDAwpd9WMfgqFoeA9vEyEUuk4kLwBKcoe1x4HG68'
          'ik918hdDSE9vDQSccA3xXHOAFOPJ8R9EeIAbTi1VwBYnbTp87X-xcPWlEP'
          'krdoUKW60tgs1aNd_Nnc9LEVVPMS390zbFxt8TN_biaBgelNgbC95sM',
      'q': 'uKlCKvKv_ZJMVcdIs5vVSU_6cPtYI1ljWytExV_skstvRSNi9r66jdd9-y'
          'BhVfuG4shsp2j7rGnIio901RBeHo6TPKWVVykPu1iYhQXw1jIABfw-MVsN'
          '-3bQ76WLdt2SDxsHs7q7zPyUyHXmps7ycZ5c72wGkUwNOjYelmkiNS0',
      'dp': 'w0kZbV63cVRvVX6yk3C8cMxo2qCM4Y8nsq1lmMSYhG4EcL6FWbX5h9yuv'
          'ngs4iLEFk6eALoUS4vIWEwcL4txw9LsWH_zKI-hwoReoP77cOdSL4AVcra'
          'Hawlkpyd2TWjE5evgbhWtOxnZee3cXJBkAi64Ik6jZxbvk-RR3pEhnCs',
      'dq': 'o_8V14SezckO6CNLKs_btPdFiO9_kC1DsuUTd2LAfIIVeMZ7jn1Gus_Ff'
          '7B7IVx3p5KuBGOVF8L-qifLb6nQnLysgHDh132NDioZkhH7mI7hPG-PYE_'
          'odApKdnqECHWw0J-F0JWnUd6D2B_1TvF9mXA2Qx-iGYn8OVV1Bsmp6qU',
      'qi': 'eNho5yRBEBxhGBtQRww9QirZsB66TrfFReG_CcteI1aCneT0ELGhYlRlC'
          'tUkTRclIfuEPmNsNDPbLoLqqCVznFbvdB7x-Tl-m0l_eFTj2KiqwGqE9PZ'
          'B9nNTwMVvH3VRRSLWACvPnSiwP8N5Usy-WRXS-V7TbpxIhvepTfE0NNo'
    },
  );
  builder.addRecipient(jwk, algorithm: 'RSA1_5');

  // set the content encryption algorithm to use
  builder.encryptionAlgorithm = 'A128CBC-HS256';

  // build the jws
  var jwe = builder.build();

  // output the compact serialization
  print('jwe compact serialization: ${jwe.toCompactSerialization()}');

  // output the json serialization
  print('jwe json serialization: ${jwe.toJson()}');
}

// decode and verify and validate a JWT
void example5() async {
  var encoded = 'eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.'
      'eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFt'
      'cGxlLmNvbS9pc19yb290Ijp0cnVlfQ.'
      'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk';

  // decode the jwt, note: this constructor can only be used for JWT inside JWS
  // structures
  var jwt = JsonWebToken.unverified(encoded);

  // output the claims
  print('claims: ${jwt.claims}');

  // create key store to verify the signature
  var keyStore = JsonWebKeyStore()
    ..addKey(JsonWebKey.fromJson({
      'kty': 'oct',
      'k':
      'AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow'
    }));

  var verified = await jwt.verify(keyStore);
  print('verified: $verified');

  // alternatively, create and verify the JsonWebToken together, this is also
  // applicable for JWT inside JWE
  jwt = await JsonWebToken.decodeAndVerify(encoded, keyStore);

  // validate the claims
  var violations = jwt.claims.validate(issuer: Uri.parse('alice'));
  print('violations: $violations');
}

// create a JWT
void example6() async {
  var claims = JsonWebTokenClaims.fromJson({
    'exp': Duration(hours: 4).inSeconds,
    'aud':"live-tv",
    'iat':DateTime.now().toString(),

  });

  // create a builder, decoding the JWT in a JWS, so using a
  // JsonWebSignatureBuilder
  var builder = JsonWebSignatureBuilder();

  // set the content
  builder.jsonContent = claims.toJson();

  // add a key to sign, can only add one for JWT
  builder.addRecipient(
      JsonWebKey.fromJson({
        'kty': 'RSA',
        'kid':pkey,
         }),

      algorithm: 'HS256');

  // build the jws
  var jws = builder.build();

  // output the compact serialization
  print('jwt compact serialization: ${jws.toCompactSerialization()}');
}

// create a JWT, sign with RS512
void example7() async {
  var claims = JsonWebTokenClaims.fromJson({
    'exp': Duration(hours: 4).inSeconds,
    'iss': 'alice',
  });

  // create a builder, decoding the JWT in a JWS, so using a
  // JsonWebSignatureBuilder
  var builder = JsonWebSignatureBuilder();

  // set the content
  builder.jsonContent = claims.toJson();

  // add a key to sign, can only add one for JWT
  var key = JsonWebKey.fromPem(File('example/jwtRS512.key').readAsStringSync());
  builder.addRecipient(key, algorithm: 'RS512');

  // build the jws
  var jws = builder.build();

  // output the compact serialization
  print('jwt compact serialization: ${jws.toCompactSerialization()}');
}

// generate a key for use with ES256 signing
void example8() async {
  var alg = JsonWebAlgorithm.getByName('ES256');

  var key = alg.generateRandomKey();
  print(JsonEncoder.withIndent(' ').convert(key));

  final hash = utf8.encode('TEST');

  var sig = key.sign(hash);
  final valid = key.verify(hash, sig);

  print('valid? $valid');
}

我一次尝试修改每个示例。很少有人说“紧凑序列化应包含3个部分”,然后我做了一些研究,意识到要生成的令牌应包含3个部分。示例2中的另一个错误是JSONWebKey无法签名。

我使用了另一个库,即https://pub.dev/packages/corsac_jwt

代码如下:

import 'package:corsac_jwt/corsac_jwt.dart';
//  ..setClaim('13', {'userId': 'xxxx'})

String pkey="sdfdsfdsfds";

void tokenGenerator() {

  var builder = new JWTBuilder();
  var token = builder
    ..audience="live-tv"
    ..issuedAt= new DateTime.now()
    ..expiresAt = new DateTime.now().add(new Duration(minutes: 3))

    ..getToken(); // returns token without signature

 var signer = new JWTRsaSha256Signer(privateKey: pkey);

  var signedToken = builder.getSignedToken(signer);
  print("token");
      print(signedToken); // prints encoded JWT
  var stringToken = signedToken.toString();

  var decodedToken = new JWT.parse(stringToken);
  // Verify signature:
  print(decodedToken.verify(signer)); // true

  // Validate claims:
//  var validator = new JWTValidator() ;// uses DateTime.now() by default
//   // set claims you wish to validate
//  Set<String> errors = validator.validate(decodedToken);
//  print(errors); // (empty list)
}

但是在这里,我得到了错误的无效私钥。如果将其更改为public,我也将获得无效的公钥。

说实话,我在精神上非常混乱,需要时间来实施。我的队友只知道一件事,只知道扑朔迷离。

下面是我们试图在颤动中实现的Java代码的方式。基本上,它要做的是将StringKey转换为PrivateKey,然后转换为令牌

import android.util.Log;

import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Date;
import java.util.concurrent.TimeUnit;


public class RSAKeyGenerator {
    private static PrivateKey getPrivateKey() throws GeneralSecurityException {
        String pKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
        KeyFactory kf = KeyFactory.getInstance("RSA");
        byte[] decode;
        decode = android.util.Base64.decode(pKey, android.util.Base64.DEFAULT);
        PKCS8EncodedKeySpec keySpecPKCS8 = new PKCS8EncodedKeySpec(decode);
        return kf.generatePrivate(keySpecPKCS8);
    }
    public static String getJwtToken() {
        final long VALIDITY_MS = TimeUnit.MINUTES.toMillis(60);
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        Date exp = new Date(nowMillis + VALIDITY_MS);
        PrivateKey privateKey = null;
        try {
            privateKey = getPrivateKey();
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        }
        String jws = Jwts.builder()
                .claim("version", "13")
                .claim("user_id", "xxxxxxxxxxxxxxxxxxx")
                .setIssuedAt(now)
                .setExpiration(exp)
                .signWith(privateKey, SignatureAlgorithm.RS256)
                .setAudience("live-tv")
                .compact();
        Log.d("111__", jws);
        SpUtil.Companion.getInstance().putString(J_TOKEN, jws);
        return jws;
    }
}

1 个答案:

答案 0 :(得分:1)

经过数小时的研究,反复试验和错误,并咨询了我的队友,我得出了最后的结论。这项工作有效。我做的错误是RSA密钥,我将它作为字符串传递给了key =“ xxxxxxxxxxxx”,但应采用以下格式

希望这对某人有帮助

long <- as.numeric(c("0.005638", "0.005648", "0.005658"))
lat <- as.numeric(c("51.62879", "51.62889", "51.62879"))
data1 <- data.frame(long, lat)


filtered_list <- 1:3
cat("## Tabs {.tabset .tabset-fade .tabset-pills}", "\n")
for (estates in filtered_list){
    cat("###", estates, "\n")
    cat("\n\n\n")
    cat("This is where the map will go ")
    
        cat("1 ")
# generate leaflet plot 
    page <- htmltools::tagList(
         leaflet() %>%
            addTiles() %>%  # Add default OpenStreetMap map tiles
            addMarkers(lng=data1$long, lat=data1$lat)
    )
    cat(as.character(page))

            cat("2 ")
    page1 <- htmltools::tagList(
         leaflet() %>%
            addTiles() %>%  # Add default OpenStreetMap map tiles
            addMarkers(lng=data1$long, lat=data1$lat, clusterOptions = markerClusterOptions())
    )
    cat(as.character(page1))



            cat("3 ")
    page2 <- htmltools::tagList(
         leaflet() %>%
            addTiles() %>%  # Add default OpenStreetMap map tiles
           addMarkers(lng=data1$long, lat=data1$lat) %>%
           addHeatmap(
    lng = data1$lat, lat = data1$long,
    blur = 20, max = 5, radius = 40
    )
    )
    cat(as.character(page2))
   
    
    }