Organize the Base64 related things (Openssl/go ...)

Source: Internet
Author: User
Tags openssl enc
This is a creation in Article, where the information may have evolved or changed.


Base64 in different languages docking, in fact, there are some small pits, have touched before.



What's the first Base64? Nanyi has a very well-written article that is very clear.



And then how do you code it?



I wrote a Base64 encoding implementation with OpenSSL:


/*
 Use openssl to do Base64 encryption and decryption.
 Author: xcl
 Date:2015-9-17
*/
#include <cstdio>
#include <cstdlib>
#include <iostream>

#include "openssl/ssl.h"
#include <openssl/bio.h>
#include <openssl/evp.h>

#if defined(WIN32) ||defined(_WIN64)
#pragma comment(lib, "libeay32.lib")
#pragma comment(lib, "ssleay32.lib")
#endif

/*
NO_PADDING : omit the last "=" of the encrypted string
NO_WRAP : omit all newline characters

Base64.DEFAULT in Android will automatically add a line break after every 76 characters.
And at the end of the string will also add a newline.
So pay attention to this when docking (such as IOS). It is recommended to select Base64.NO_WRAP type.

When OpenSSL's command line performs Base64, it automatically adds a newline character for every 64 characters, and automatically adds a newline at the end.
The decoding command line is as follows:
Echo "Hello"|openssl enc -base64
Echo "SGVsbG8K"|openssl enc -base64 -d

*/
Enum Base64{ NO_PADDING = 0, NO_WRAP};

Std::string Decode(std::string data,const int mode) {
Printf("[Decode] before decryption: %s\r\n", data.c_str());
Size_t length = data.length();
If (length == 0)return "";

BIO *b64 = BIO_new(BIO_f_base64());
If (mode == Base64::NO_WRAP) {
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
}

BIO *mem = nullptr;
Mem = BIO_new_mem_buf(const_cast<char *>(data.c_str()), -1);
Mem = BIO_push(b64, mem);

//char inbuf[512];
//int inlen;
//while ((inlen = BIO_read(b64, inbuf, 512)) > 0) {
// printf("after decryption: %s \n\r\n", inbuf);
//}
Char * buffer = (char *)malloc(length);
Memset(buffer, 0, length);
BIO_read(mem, buffer, length);
Std::string ret(buffer);
Free(buffer);

BIO_free_all(mem);
Printf("[Decode] after decryption: %s\r\n", ret.c_str());
Return ret;
}


Std::string Encode(std::string data,const int mode) {
Printf("[Encode] before encryption: %s\r\n", data.c_str());
If (data.length() == 0)return "";

//When writing, use base64 encoding
BIO *b64 = BIO_new(BIO_f_base64());

// If BIO_FLAGS_BASE64_NO_NL is turned on, it will be passed with "\n" or "Hello\n".
// Otherwise, two characters will be lost after the restore.
If (Base64::NO_WRAP == mode) {
Data.append("\n");
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
}

// Create a memory BIO
BIO *mem = BIO_new(BIO_s_mem());
B64 = BIO_push(b64, mem);

BIO_write(b64, data.c_str(), data.length());
BIO_flush(b64);
//BIO_puts(b64, data.c_str());

/ / Get the string after base64
BUF_MEM *pBuf = nullptr;
BIO_get_mem_ptr(mem, &pBuf);
Std::string ret(pBuf->data);
Free(pBuf);

BIO_set_close(b64, BIO_NOCLOSE);
BIO_free_all(b64);

Printf("[Encode] after encryption: %s\r\n", ret.c_str());
Return ret;
}

Void main() {
Std::string s = "Hello";

Printf("////////////////////////////////\r\n");
Printf("NO_PADDING:\r\n");
Base64 mode = Base64::NO_PADDING;
s = Encode(s,mode);
    Decode(s,mode);

Printf("////////////////////////////////\r\n");
Printf("NO_WRAP:\r\n");

s = "Hello";
Mode = Base64::NO_WRAP;
s = Encode(s, mode);
Decode(s, mode);

System("pause");
}

/*
/////////////////////////////////
NO_PADDING:
[Encode] Before encryption: Hello
[Encode] After encryption: SGVsbG8=

[Decode] Before decryption: SGVsbG8=

[Decode] After decryption: Hello
/////////////////////////////////
NO_WRAP:
[Encode] Before encryption: Hello

[Encode] After encryption: SGVsbG8K
[Decode] Before decryption: SGVsbG8K
[Decode] After decryption: Hello

Please press any key to continue. . .
*/

For Golang, the official website provides a good example of the standard Base64 and URL encoding I'm going to post this example here:


package main

import b64 "encoding/base64"
import "fmt"

func main() {
	data := "abc123!?$*&()'-=@~"

	sEnc := b64.StdEncoding.EncodeToString([]byte(data))
    fmt.Println(sEnc)
	
	
	sDec, _ := b64.StdEncoding.DecodeString(sEnc)
    fmt.Println(string(sDec))
    fmt.Println()
	
   uEnc := b64.URLEncoding.EncodeToString([]byte(data))
    fmt.Println(uEnc)
    uDec, _ := b64.URLEncoding.DecodeString(uEnc)
    fmt.Println(string(uDec))
}


$ go run base64-encoding.go
YWJjMTIzIT8kKiYoKSctPUB+
abc123!?$*&()'-=@~

YWJjMTIzIT8kKiYoKSctPUB-
abc123!?$*&()'-=@~



If you are interested in how go is implemented, this has the source code.



Well, that's roughly all.






blog:http://blog.csdn.net/xcl168




Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.