玲珑杯-base64加密-CSDN博客

75 阅读1分钟

玲珑杯-base64加密

import java.util.Base64;
import java.io.BufferedInputStream;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Main {
	
	public static void main(String[] args) {
		//加密后的文本
		String key = "d2hhdCBpcyB0aGUgcmVtYWluZGVyIHdoZW4gdGhlIG51bWJlciBpcyBkaXZpZGVkIGJ5IDIwMTc/";
		String value = new String(Base64.getDecoder().decode(key),StandardCharsets.UTF_8);
		//System.out.println(value);//本行取消注释,就可以看到题意,java解题开挂
		
		Scanner sc = new Scanner (new BufferedInputStream(System.in));
		int t = sc.nextInt();
		while(t-- != 0) {
			System.out.println(sc.nextInt() % 2017);
		}
		sc.close();
	}	
}


\

C++模拟base64加密算法,本来我是想写解密算法呢?额,一不小心写反了,写成了加密算法。。。。尴尬

const char str[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
string value = "what is the remainder when the number is divided by 2017?";
//string key = "d2hhdCBpcyB0aGUgcmVtYWluZGVyIHdoZW4gdGhlIG51bWJlciBpcyBkaXZpZGVkIGJ5IDIwMTc/";
string base64Encode(string source) { //参数为明文 
	string code01, key;
	for (int i = 0; i < source.length(); ++i) {
		int ch = source[i], num;
		for (int j = 0; j < 8; ++j) {
			num = (ch & 128)  == 0 ? 0: 1;
			ch <<= 1;
			code01.append(1,  num + '0');
		}	
	}
	int remainder = code01.length() % 6;
	if (remainder != 0)
		code01.insert(code01.end() - remainder, 6 - remainder, '0');
	int cnt = code01.length() / 6;
	for (int i = 0; i < code01.length(); i += 6) {
		int num = 0;
		for (int j = 0; j < 6; ++j)
			num += (code01[i + j] - '0') * (1 << (5 - j));
		char ch = str[num];
		key.append(1, ch);
	}
	return key; //返回加密后的暗文 
}

\

base64解码(其实解码,和加密算法类似)

const char str[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";;
string key = "d2hhdCBpcyB0aGUgcmVtYWluZGVyIHdoZW4gdGhlIG51bWJlciBpcyBkaXZpZGVkIGJ5IDIwMTc/";
string base64Decode(string key) { //参数为暗文 
	string code01, value;
	int mod = 8;
	for (int i = 0; i < key.length(); ++i) {
		int ch = (strchr(str, key[i]) - str), num;
		for (int j = 0; j < 6; ++j) {
			num = (ch & 32) == 0 ? 0 : 1; // 128 - > 32
			ch <<= 1;
			code01.append(1, num + '0');
		}
	}
	int remainder = code01.length() % mod;
	if (remainder != 0)
		code01.insert(code01.end() - remainder, mod - remainder, '0');
	int cnt = code01.length() / mod;
	for (int i = 0; i < code01.length(); i += mod) {
		int num = 0;
		for (int j = 0; j < mod; ++j)
			num += (code01[i + j] - '0') * (1 << (mod - 1 - j));
		char ch = num;
		value.append(1, ch);
	}
	return value; //返回解密后的明文 
}



\