“IllegalArgumentException: bad base-64” while trying to use Base64 on Android 1.5 [closed]

孤人 提交于 2019-11-30 10:35:54
Venkatesh S
public class Crypto {
   public static String encrypt(String value, String key) throws GeneralSecurityException {
    SecretKeySpec sks = new SecretKeySpec(hexStringToByteArray(key), "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, sks, cipher.getParameters());
    byte[] encrypted = cipher.doFinal(value.getBytes());
    return byteArrayToHexString(encrypted);
}

public static String decrypt(String message, String key) throws GeneralSecurityException {
    SecretKeySpec sks = new SecretKeySpec(hexStringToByteArray(key), "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE, sks);
    byte[] decrypted = cipher.doFinal(hexStringToByteArray(message));
    return new String(decrypted);
}   

private static String byteArrayToHexString(byte[] b){
    StringBuffer sb = new StringBuffer(b.length * 2);
    for (int i = 0; i < b.length; i++){
        int v = b[i] & 0xff;
        if (v < 16) {
            sb.append('0');
        }
        sb.append(Integer.toHexString(v));
    }
    return sb.toString().toUpperCase();
}

private static byte[] hexStringToByteArray(String s) {
    byte[] b = new byte[s.length() / 2];
    for (int i = 0; i < b.length; i++){
        int index = i * 2;
        int v = Integer.parseInt(s.substring(index, index + 2), 16);
        b[i] = (byte)v;
    }
    return b;
}
  }

above class will help in encrypt and decrypt string without base64

usage of above class

try {
    String key = UUID.randomUUID().toString().replaceAll("-", "");
    String src = "Hello world!";
    String tag1 = Crypto.encrypt(src, key);
    String tag2 = Crypto.decrypt(tag1, key);
    logger.info(src);
    logger.info(tag1);
    logger.info(tag2);
} catch (Exception e) {
    logger.error("", e);
}
private static String encrypt(Context cont, String value) {
    try {
        return Base64.encodeToString(value.getBytes(), Base64.DEFAULT);
    }
catch (IllegalArgumentException e) {
            // TODO: handle exception
        }
 catch (Exception e) {
        throw new RuntimeException(e);
    }
}

private static String decrypt(Context cont, String value) {
    try {
        return new String(Base64.decode(value, Base64.DEFAULT));
    }
catch (IllegalArgumentException e) {
            // TODO: handle exception
        } 
catch (Exception e) {
        throw new RuntimeException(e);
    }
}

add illegal argument exception catch ..... I hope it will work

sunil

have you seen this ?

How to encode a string with Base64 in Android?

They are using Base64 Library from iHarder.net to encode/decode strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!