Base64 encode and decode example code

后端 未结 12 940
遥遥无期
遥遥无期 2020-11-22 15:00

Does anyone know how to decode and encode a string in Base64 using the Base64. I am using the following code, but it\'s not working.

String source = \"passwo         


        
12条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 15:29

    Based on the previous answers I'm using the following utility methods in case anyone would like to use it.

        /**
     * @param message the message to be encoded
     *
     * @return the enooded from of the message
     */
    public static String toBase64(String message) {
        byte[] data;
        try {
            data = message.getBytes("UTF-8");
            String base64Sms = Base64.encodeToString(data, Base64.DEFAULT);
            return base64Sms;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    
        return null;
    }
    
    /**
     * @param message the encoded message
     *
     * @return the decoded message
     */
    public static String fromBase64(String message) {
        byte[] data = Base64.decode(message, Base64.DEFAULT);
        try {
            return new String(data, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    
        return null;
    }
    

提交回复
热议问题