package com.yutou.biliapi.net; import com.yutou.biliapi.bean.login.CheckCookieBean; import com.yutou.common.inter.IHttpApiCheckCallback; import com.yutou.common.okhttp.HttpCallback; import com.yutou.common.utils.RSAUtils; import okhttp3.Headers; import javax.crypto.Cipher; import javax.crypto.spec.OAEPParameterSpec; import javax.crypto.spec.PSource; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.security.KeyFactory; import java.security.PublicKey; import java.security.spec.MGF1ParameterSpec; import java.security.spec.X509EncodedKeySpec; import java.util.Base64; public class BiliCookieManager { public static final int COOKIE_INVALID = -101; public static final int COOKIE_SUCCESS = 0; private static final String PUBLIC_KEY = "-----BEGIN PUBLIC KEY-----\n" + "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDLgd2OAkcGVtoE3ThUREbio0Eg\n" + "Uc/prcajMKXvkCKFCWhJYJcLkcM2DKKcSeFpD/j6Boy538YXnR6VhcuUJOhH2x71\n" + "nzPjfdTcqMz7djHum0qSZA0AyCBDABUqCrfNgCiJ00Ra7GmRj+YCK1NJEuewlb40\n" + "JNrRuoEUXpabUzGB8QIDAQAB\n" + "-----END PUBLIC KEY-----"; public void checkCookie(IHttpApiCheckCallback callback){ BiliLoginNetApiManager.getInstance().getLoginApi(null) .checkCookie().enqueue(new HttpCallback() { @Override public void onResponse(Headers headers, int code, String status, CheckCookieBean response, String rawResponse) { if(code==-101){ // TODO cookie失效,需要重新登录 callback.onError(COOKIE_INVALID,"cookie失效,需要重新登录"); return; } if(response.isRefresh()){ refreshCookie(); } callback.onSuccess(COOKIE_SUCCESS); } @Override public void onFailure(Throwable throwable) { } }); } /** * 文档地址 */ private void refreshCookie(){ try { String refreshTime = String.format("refresh_%d", System.currentTimeMillis()); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); String publicKeyStr = PUBLIC_KEY .replace("-----BEGIN PUBLIC KEY-----", "") .replace("-----END PUBLIC KEY-----", "") .replace("\n", "") .trim(); byte[] publicBytes = Base64.getDecoder().decode(publicKeyStr); X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicBytes); PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec); String algorithm = "RSA/ECB/OAEPPadding"; Cipher cipher = Cipher.getInstance(algorithm); cipher.init(Cipher.ENCRYPT_MODE, publicKey); // Encode the plaintext to bytes byte[] plaintextBytes = refreshTime.getBytes(StandardCharsets.UTF_8); // Add OAEP padding to the plaintext bytes OAEPParameterSpec oaepParams = new OAEPParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT); cipher.init(Cipher.ENCRYPT_MODE, publicKey, oaepParams); // Encrypt the padded plaintext bytes byte[] encryptedBytes = cipher.doFinal(plaintextBytes); // Convert the encrypted bytes to a Base64-encoded string String encrypted = new BigInteger(1, encryptedBytes).toString(16); }catch (Exception e){ e.printStackTrace(); } } }