Base64

本文介绍了一个简单的Base64编码和解码程序的实现方法。该程序使用C语言编写,包括对输入数据进行Base64编码以及将Base64编码的数据还原为原始数据的功能。适用于文件的转换处理。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <io.h>
#include <fcntl.h>
#include <stdbool.h>

#ifndef MAX_PATH
#define MAX_PATH 256
#endif

const char * base64char = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

char * base64_encode( const unsigned char * bindata, char * base64, int binlength )
{
    int i, j;
    unsigned char current;

    for ( i = 0, j = 0 ; i < binlength ; i += 3 )
    {
        current = (bindata[i] >> 2) ;
        current &= (unsigned char)0x3F;
        base64[j++] = base64char[(int)current];

        current = ( (unsigned char)(bindata[i] << 4 ) ) & ( (unsigned char)0x30 ) ;
        if ( i + 1 >= binlength )
        {
            base64[j++] = base64char[(int)current];
            base64[j++] = '=';
            base64[j++] = '=';
            break;
        }
        current |= ( (unsigned char)(bindata[i+1] >> 4) ) & ( (unsigned char) 0x0F );
        base64[j++] = base64char[(int)current];

        current = ( (unsigned char)(bindata[i+1] << 2) ) & ( (unsigned char)0x3C ) ;
        if ( i + 2 >= binlength )
        {
            base64[j++] = base64char[(int)current];
            base64[j++] = '=';
            break;
        }
        current |= ( (unsigned char)(bindata[i+2] >> 6) ) & ( (unsigned char) 0x03 );
        base64[j++] = base64char[(int)current];

        current = ( (unsigned char)bindata[i+2] ) & ( (unsigned char)0x3F ) ;
        base64[j++] = base64char[(int)current];
    }
    base64[j] = '\0';
    return base64;
}

int base64_decode( const char * base64, unsigned char * bindata )
{
    int i, j;
    unsigned char k;
    unsigned char temp[4];
    for ( i = 0, j = 0; base64[i] != '\0' ; i += 4 )
    {
        memset( temp, 0xFF, sizeof(temp) );
        for ( k = 0 ; k < 64 ; k ++ )
        {
            if ( base64char[k] == base64[i] )
                temp[0]= k;
        }
        for ( k = 0 ; k < 64 ; k ++ )
        {
            if ( base64char[k] == base64[i+1] )
                temp[1]= k;
        }
        for ( k = 0 ; k < 64 ; k ++ )
        {
            if ( base64char[k] == base64[i+2] )
                temp[2]= k;
        }
        for ( k = 0 ; k < 64 ; k ++ )
        {
            if ( base64char[k] == base64[i+3] )
                temp[3]= k;
        }

        bindata[j++] = ((unsigned char)(((unsigned char)(temp[0] << 2))&0xFC)) |
                ((unsigned char)((unsigned char)(temp[1]>>4)&0x03));
        if ( base64[i+2] == '=' )
            break;

        bindata[j++] = ((unsigned char)(((unsigned char)(temp[1] << 4))&0xF0)) |
                ((unsigned char)((unsigned char)(temp[2]>>2)&0x0F));
        if ( base64[i+3] == '=' )
            break;

        bindata[j++] = ((unsigned char)(((unsigned char)(temp[2] << 6))&0xF0)) |
                ((unsigned char)(temp[3]&0x3F));
    }
    return j;
}

void encode(FILE * fp_in, FILE * fp_out)
{
    unsigned char bindata[2050];
    char base64[4096];
    size_t bytes;
    while ( !feof( fp_in ) )
    {
        bytes = fread( bindata, 1, 2049, fp_in );
        base64_encode( bindata, base64, bytes );
        fprintf( fp_out, "%s", base64 );
    }
}

void decode(FILE * fp_in, FILE * fp_out)
{
    int i;
    unsigned char bindata[2050];
    char base64[4096];
    size_t bytes;
    while ( !feof( fp_in ) )
    {
        for ( i = 0 ; i < 2048 ; i ++ )
        {
            base64[i] = fgetc(fp_in);
            if ( base64[i] == EOF )
                break;
            else if ( base64[i] == '\n' || base64[i] == '\r' )
                i --;
        }
        bytes = base64_decode( base64, bindata );
        fwrite( bindata, bytes, 1, fp_out );
    }
}

void help(const char * filepath)
{
    fprintf( stderr, "Usage: %s [-d] [input_filename] [-o output_filepath]\n", filepath );
    fprintf( stderr, "\t-d\tdecode data\n" );
    fprintf( stderr, "\t-o\toutput filepath\n\n" );
}

int main(int argc, char * argv[])
{
    FILE * fp_input = NULL;
    FILE * fp_output = NULL;
    bool isencode = true;
    bool needHelp = false;
    int opt = 0;
    char input_filename[MAX_PATH] = "";
    char output_filename[MAX_PATH] = "";

    opterr = 0;
    while ( (opt = getopt(argc, argv, "hdo:")) != -1 )
    {
        switch(opt)
        {
        case 'd':
            isencode = false;
            break;
        case 'o':
            strncpy(output_filename, optarg, sizeof(output_filename));
            output_filename[sizeof(output_filename)-1] = '\0';
            break;
        case 'h':
            needHelp = true;
            break;
        default:
            fprintf(stderr, "%s: invalid option -- %c\n", argv[0], optopt);
            needHelp = true;
            break;
        }
    }
    if ( optind < argc )
    {
        strncpy(input_filename, argv[optind], sizeof(input_filename));
        input_filename[sizeof(input_filename)-1] = '\0';
    }

    if (needHelp)
    {
        help(argv[0]);
        return EXIT_FAILURE;
    }

    if ( !strcmp(input_filename, "") )
    {
        fp_input = stdin;
        if (isencode)
            _setmode( _fileno(stdin), _O_BINARY );
    }
    else
    {
        if (isencode)
            fp_input = fopen(input_filename, "rb");
        else
            fp_input = fopen(input_filename, "r");
    }
    if ( fp_input == NULL )
    {
        fprintf(stderr, "Input file open error\n");
        return EXIT_FAILURE;
    }

    if ( !strcmp(output_filename, "") )
    {
        fp_output = stdout;
        if (!isencode)
            _setmode( _fileno(stdout), _O_BINARY );
    }
    else
    {
        if (isencode)
            fp_output = fopen(output_filename, "w");
        else
            fp_output = fopen(output_filename, "wb");
    }
    if ( fp_output == NULL )
    {
        fclose(fp_input);
        fp_input = NULL;
        fprintf(stderr, "Output file open error\n");
        return EXIT_FAILURE;
    }

    if (isencode)
        encode(fp_input, fp_output);
    else
        decode(fp_input, fp_output);
    fclose(fp_input);
    fclose(fp_output);
    fp_input = fp_output = NULL;
    return EXIT_SUCCESS;
}

 

06-07
### Base64 编码与解码的使用方法 Base64 是一种基于 64 个可打印字符来表示二进制数据的编码方式。它主要用于将二进制数据转换为文本格式,以便在需要纯文本传输的场景中使用。以下是 Base64 编码和解码的基本使用方法: #### 1. 编码过程 在 Java 中,可以使用 `android.util.Base64` 或 `java.util.Base64`(JDK 8 及以上版本)来实现 Base64 编码。以下是一个示例代码,展示如何对字符串进行 Base64 编码[^1]。 ```java import android.util.Base64; public class Base64Example { public static void main(String[] args) { String str = "I love Android"; // 将字符串转换为字节数组并进行 Base64 编码 byte[] encodedBytes = Base64.encode(str.getBytes(), Base64.NO_WRAP); String encodedString = new String(encodedBytes); System.out.println("Base64 编码结果: " + encodedString); } } ``` #### 2. 解码过程 解码是编码的逆操作。同样可以使用 `android.util.Base64` 或 `java.util.Base64` 来实现。以下是一个示例代码,展示如何对 Base64 编码后的字符串进行解码[^1]。 ```java import android.util.Base64; public class Base64DecodeExample { public static void main(String[] args) { String encodedString = "SSBsb3ZlIEFuZHJvaWQ="; // 示例编码后的字符串 // 对 Base64 编码的字符串进行解码 byte[] decodedBytes = Base64.decode(encodedString, Base64.NO_WRAP); String decodedString = new String(decodedBytes); System.out.println("Base64 解码结果: " + decodedString); } } ``` #### 3. JDK 内置工具的使用 在 JDK 中,`sun.misc.BASE64Encoder` 和 `sun.misc.BASE64Decoder` 曾被广泛使用,但这些类自 JDK 9 起已被废弃。推荐使用 `java.util.Base64` 类作为替代方案[^2]。以下是一个使用 `java.util.Base64` 的示例代码: ```java import java.util.Base64; public class Base64JdkExample { public static void main(String[] args) { String text = "需要编码的数据"; // 编码 String encodedText = Base64.getEncoder().encodeToString(text.getBytes()); System.out.println("编码结果: " + encodedText); // 解码 byte[] decodedBytes = Base64.getDecoder().decode(encodedText); String decodedText = new String(decodedBytes); System.out.println("解码结果: " + decodedText); } } ``` #### 4. Base64 编码的特点 - **优点**:Base64 编码能够将任意二进制数据转换为 ASCII 字符串,适合在网络协议或存储系统中使用。 - **缺点**:编码后的数据长度会增加约 33%,并且编码效率相对较低[^2]。 #### 注意事项 - 在编码时,可以通过设置不同的标志(如 `Base64.NO_WRAP`、`Base64.DEFAULT` 等)控制输出格式。例如,`Base64.NO_WRAP` 表示不换行处理,而 `Base64.DEFAULT` 则会在每 76 个字符后自动换行。 - 解码时必须确保使用的标志与编码时一致,否则可能导致解码失败。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值