Я пытаюсь войти в Steam с параметрами URL и зашифровать пароль с помощью ключа RSA, который был отправлен Steam, выдает ошибку неверного пароля - PullRequest
0 голосов
/ 23 апреля 2020

Я хочу знать, является ли мое шифрование пароля с помощью ключа RSA корректным и правильного типа. Я предоставляю полный код, если есть другие проблемы с ним. Я также поместил C# код, который я нашел в Интернете, который работает для шифрования парового пароля.

Заранее благодарю за помощь.

Я получаю ключ RSA от steam со следующим кодом:

private String generateRsaKey(){

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://store.steampowered.com/login/getrsakey/?username=" + USERNAME))
                .headers("User-Agent", "Mozilla/5.0", "Content-Type", "application/json; charset=UTF-8")
                .POST(HttpRequest.BodyPublishers.ofString(""))
                .build();
        try{
            //Send the request through our HttpClient and get a HttpResponse in form of json String.
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            //if response code is 200 it means that the request was received by server.
            if(response.statusCode() == 200){
                return response.body();
            }else{
                System.out.println("Status-Code: " + response.statusCode());
                return response.toString();
            }
        }
        catch(IOException | InterruptedException e){
            System.out.println("IOException or InterruptedException in generateRSAKey method : " + e.getMessage());
            return e.getMessage();
        }
    }

Получен ответ Json следующего содержания:

{
  "success": true,
  "publickey_mod": "a34c87e072501474c5b75dbfb179bd240123bdcda2f79c450b3224bdbe2527ded280706a727fcced28a4a00187165285df8bf0c37721c682808502d89ac05d1cb521babdfee8d4cd0e12169a139338418b0b8ddb0d0066e027bd1c4bb18928b996416a1f671e0754428c53b2234cb5cfc67adbd93006d6c4ca4f5459b8cb22e675ee04e045387db331659e3143c71c941c092fe56e665f8ae21c73153a31a287fb85178d51d710ebb33ad6b437af5fe073b4a2a969920364fd595f824d4b0bca41216b66865fc8e020ef3b36ddc3613f6fdd8559471cc7165384562e20ca422f32a12e9a064279d80ad03d1d111922993e8e62e94da9ae4cf0bd7a08708f047b",
  "publickey_exp": "010001",
  "timestamp": "118890450000",
  "token_gid": "1a6dcc928b348af4"
}

Следующий код кодирует пароль:

//Getter for RSA_KEY 
    private Map<String, String> getRSAKey_Map(){
        Map<String, String> rsaKeyMap = new HashMap<>();
        String rsaJsonString = generateRsaKey();
        try {
            JSONObject rsaJson = (JSONObject) jsonParser.parse(rsaJsonString);
            rsaKeyMap.put("publickey_mod", (String) rsaJson.get("publickey_mod"));
            rsaKeyMap.put("publickey_exp", (String) rsaJson.get("publickey_exp"));
            rsaKeyMap.put("timestamp", (String) rsaJson.get("timestamp"));
            return rsaKeyMap;
        }
        catch(ParseException e){
            System.out.println("getRSAKey_Map in LoginExecutor Failed to parse RSAKey : " + e.getMessage());
            return null;
        }
    }
    //Encrypt Password with the received RSA key
    private String encryptPassWordWithRSAKey() {
        BigInteger module = new BigInteger(this.getRSAKey_Map().get("publickey_mod"), 16);
        BigInteger exponent = new BigInteger(this.getRSAKey_Map().get("publickey_exp"), 16);
        try {
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(module, exponent);
            RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(publicKeySpec);

            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] encryptedPassWord = cipher.doFinal(PASSWORD.getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(encryptedPassWord);
        } catch (IllegalBlockSizeException |BadPaddingException|NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeyException | InvalidKeySpecException e) {
            System.out.println("Exception in encryptPassWordWithRSAKey method of LoginExecutor");
            e.printStackTrace();
            return null;
        }
    }
    private String getEncodedPassword(){
        return this.encryptPassWordWithRSAKey();
    }

Это C# код, который я нашел в сети, который работает:

RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();

RSA.ImportParameters(new RSAParameters
{
    Modulus = HexToBytes(Result.publickey_mod),
    Exponent = HexToBytes(Result.publickey_exp)
});
string EncryptedPassword = Convert.ToBase64String(RSA.Encrypt(Encoding.UTF8.GetBytes("MyPasswordHere"), false));

И, наконец, форма зашифрованного пароля выше используется для входа в систему:

private String doLogin(){
        Map<String, String> params_Required_DoLogin = new HashMap<>();
        params_Required_DoLogin.put("password", this.getEncodedPassword());
        params_Required_DoLogin.put("username", USERNAME);
        params_Required_DoLogin.put("rsatimestamp", this.getRSAKey_Map().get("timestamp"));
        params_Required_DoLogin.put("oauth_client_id", "DE45CD61");

        Map<String, String> params_Optional_DoLogin = new HashMap<>();
        params_Optional_DoLogin.put("twofactorcode", "");
        params_Optional_DoLogin.put("emailauth", "");
        params_Optional_DoLogin.put("loginfriendlyname", "");
        params_Optional_DoLogin.put("CAPTCHAgid", "");
        params_Optional_DoLogin.put("CAPTCHA_text", "");
        params_Optional_DoLogin.put("remember_login", "");
        params_Optional_DoLogin.put("donotcache", "");

        StringBuilder uri_DoLogin_StringBuilder = new StringBuilder();
        uri_DoLogin_StringBuilder .append("https://steamcommunity.com/mobilelogin/dologin/?");
        int count = 0;
        for (String key : params_Required_DoLogin.keySet()){
            if(count == 0){
                uri_DoLogin_StringBuilder .append(key+"="+params_Required_DoLogin.get(key));
            }else{
                uri_DoLogin_StringBuilder .append("&"+ key+"="+params_Required_DoLogin.get(key));
            }
            count++;
        }
        String doLogin_URI = uri_DoLogin_StringBuilder.toString();

        HttpRequest request_DoLogin = HttpRequest.newBuilder()
                .uri(URI.create(doLogin_URI))
                .header("User-Agent", "Mozilla/5.0")
                .build();
        try {
            HttpResponse loginResponse = client.send(request_DoLogin, HttpResponse.BodyHandlers.ofString());
            if(loginResponse.statusCode() == 200){
                return loginResponse.body().toString();
            }else{
                System.out.println("Status-Code: " + loginResponse.statusCode());
                return loginResponse.toString();
            }
        } catch (IOException | InterruptedException e) {
            return "Exception Sending request : " + e.getMessage();
        }
    }
    public void doLogin_Execute(){
        System.out.println(doLogin());
    }

Ответ Steam на логин:

{
  "success": false,
  "requires_twofactor": false,
  "message": "The account name or password that you have entered is incorrect.",
  "clear_password_field": true,
  "captcha_needed": false,
  "captcha_gid": -1
}

Я не понимаю, в какой момент я иду не так. Возможно шифрование? Спасибо за чтение кода. Вся помощь приветствуется.

...