All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.fastchar.security.template.rsa_android Maven / Gradle / Ivy

static final AtomicInteger atomicInteger = new AtomicInteger();
public static String getToken() {
    try {
        Cipher cipher = Cipher.getInstance("RSA/NONE/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, getPublicKey());
        String content="${key}_android"+System.currentTimeMillis()+ atomicInteger.incrementAndGet();
        byte[] data = content.getBytes(Charset.forName("UTF-8"));

        int inputLen = data.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > 117) {
                cache = cipher.doFinal(data, offSet, 117);
            } else {
                cache = cipher.doFinal(data, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * 117;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        return Base64.encodeToString(encryptedData, Base64.DEFAULT).replace("\n", "");
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}


private static Key getPublicKey() {
    try {
        String publicKey="${publicKey}";
        byte[] keyBytes=Base64.decode(publicKey, Base64.DEFAULT);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePublic(keySpec);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy