客户端加密

   由于Android应用没有像web开发中的session机制,所以采用PHPSESSID的方式,是没有办法获取客户端登录状态的。
        这种情况下,如何在用户登录后,服务器端获取用户登录状态并保持,就必须采用一种“握手”的方式。
        每个手机都有自己的IMEI号,那么能不能通过这个标识去做认证呢?
        经过试验,答案是可以。
        客户端在请求服务器端的时候,请求参数为 IMEI (param 1)及 IMEI&UA (param 2)经过加密的字符串;服务器端对客户端传递的两个参数进行解密,比对两个IME<span style="white-space:pre">	</span>I值是否相同。如果相同,返回token给客户端,以后每次客户端请求服务器端的时候,都携带该token。这样服务器就可以获取用户登录状态了。
        这里,我采用的DES加密的方式,由于PHP和Java的DES加密是有差异的,所以单独进行处理。
public class DESencode {
	public static final String ALGORITHM_DES = "DES/CBC/PKCS5Padding";
	/**
	 * DES算法,加密
	 * @param data 待加密字符串
	 * @param key 加密私钥,长度不能够小于8位
	 * @return 加密后的字节数组,一般结合Base64编码使用
	 * @throws CryptException 异常
	 */
	public static String encode(String key, String data) throws Exception {
		return encode(key, data.getBytes());
	}
	/**
	 * DES算法,加密
	 * @param data 待加密字符串
	 * @param key 加密私钥,长度不能够小于8位
	 * @return 加密后的字节数组,一般结合Base64编码使用
	 * @throws CryptException 异常
	 */
	public static String encode(String key, byte[] data) throws Exception {
		try {
			DESKeySpec dks = new DESKeySpec(key.getBytes());
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			// key的长度不能够小于8位字节
			Key secretKey = keyFactory.generateSecret(dks);
			Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
			IvParameterSpec iv = new IvParameterSpec("12345678".getBytes());
			AlgorithmParameterSpec paramSpec = iv;
			cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec);
			byte[] bytes = cipher.doFinal(data);
			return Base64.encode(bytes);
		} catch (Exception e) {
			throw new Exception(e);
		}
	}
	/**
	 * DES算法,解密
	 * @param data 待解密字符串
	 * @param key 解密私钥,长度不能够小于8位
	 * @return 解密后的字节数组
	 * @throws Exception 异常
	 */
	public static byte[] decode(String key, byte[] data) throws Exception {
		try {
			SecureRandom sr = new SecureRandom();
			DESKeySpec dks = new DESKeySpec(key.getBytes());
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			// key的长度不能够小于8位字节
			Key secretKey = keyFactory.generateSecret(dks);
			Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
			IvParameterSpec iv = new IvParameterSpec("12345678".getBytes());
			AlgorithmParameterSpec paramSpec = iv;
			cipher.init(Cipher.DECRYPT_MODE, secretKey, paramSpec);
			return cipher.doFinal(data);
		} catch (Exception e) {
			throw new Exception(e);
		}
	}
	/**
	 * 获取编码后的值
	 * @param key
	 * @param data
	 * @throws Exception
	 */
	public static String decodeValue(String key, String data) {
		byte[] datas;
		String value = null;
		try {
			if (System.getProperty("os.name") != null
					&& (System.getProperty("os.name").equalsIgnoreCase("sunos") || System
							.getProperty("os.name").equalsIgnoreCase("linux"))) {
				datas = decode(key, Base64.decode(data));
			} else {
				datas = decode(key, Base64.decode(data));
			}
			value = new String(datas);
		} catch (Exception e) {
			value = "";
		}
		return value;
	}
	/**
	 * test
	 * @param key : 12345678
	 */
	public static void main(String[] args) throws Exception {
		System.out.println("明:cychai ;密:" + Des2.encode("12345678", "cychai"));
	}

}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是一个简单的示例代码,可以实现将不同用户的字符串加密保存到本地。 ```cpp #include <iostream> #include <fstream> #include <string> #include <map> #include <openssl/evp.h> #include <openssl/rand.h> using namespace std; class Encryption { public: Encryption(const string& key) : m_key(key) {} string encrypt(const string& plaintext) const { // 生成随机向量 unsigned char iv[EVP_MAX_IV_LENGTH]; RAND_bytes(iv, EVP_MAX_IV_LENGTH); // 初始化加密上下文 EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new(); EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), nullptr, (const unsigned char*)m_key.c_str(), iv); // 分配输出缓冲区 int outlen = plaintext.length() + EVP_MAX_BLOCK_LENGTH; unsigned char* outbuf = new unsigned char[outlen]; // 执行加密操作 int ciphertext_len = 0; EVP_EncryptUpdate(ctx, outbuf, &outlen, (const unsigned char*)plaintext.c_str(), plaintext.length()); ciphertext_len += outlen; EVP_EncryptFinal_ex(ctx, outbuf + ciphertext_len, &outlen); ciphertext_len += outlen; // 将密文和随机向量合并 string ciphertext((char*)iv, EVP_MAX_IV_LENGTH); ciphertext += string((char*)outbuf, ciphertext_len); // 释放内存 delete[] outbuf; EVP_CIPHER_CTX_free(ctx); return ciphertext; } string decrypt(const string& ciphertext) const { // 提取随机向量和密文 unsigned char iv[EVP_MAX_IV_LENGTH]; memcpy(iv, ciphertext.c_str(), EVP_MAX_IV_LENGTH); string data(ciphertext, EVP_MAX_IV_LENGTH, string::npos); // 初始化解密上下文 EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new(); EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), nullptr, (const unsigned char*)m_key.c_str(), iv); // 分配输出缓冲区 int outlen = data.length() + EVP_MAX_BLOCK_LENGTH; unsigned char* outbuf = new unsigned char[outlen]; // 执行解密操作 int plaintext_len = 0; EVP_DecryptUpdate(ctx, outbuf, &outlen, (const unsigned char*)data.c_str(), data.length()); plaintext_len += outlen; EVP_DecryptFinal_ex(ctx, outbuf + plaintext_len, &outlen); plaintext_len += outlen; // 释放内存 string plaintext((char*)outbuf, plaintext_len); delete[] outbuf; EVP_CIPHER_CTX_free(ctx); return plaintext; } private: string m_key; }; int main() { map<string, string> user_data = { {"user1", "data1"}, {"user2", "data2"} }; Encryption encrypter("my_secret_key"); for (const auto& [user, data] : user_data) { // 加密并保存到文件 string encrypted = encrypter.encrypt(data); ofstream file(user + ".dat", ios::binary); file.write(encrypted.c_str(), encrypted.length()); file.close(); // 读取并解密文件 ifstream infile(user + ".dat", ios::binary); string ciphertext((istreambuf_iterator<char>(infile)), istreambuf_iterator<char>()); string decrypted = encrypter.decrypt(ciphertext); cout << user << ": " << decrypted << endl; } return 0; } ``` 在此示例中,我们使用 OpenSSL 库中的 EVP 加密算法进行加密和解密。具体来说,我们使用 AES-256-CBC 加密算法来加密数据。在加密过程中,我们使用一个固定的密钥对数据进行加密。在实际情况中,你可能需要使用更加安全的密钥管理方案,例如使用密钥派生函数生成密钥。 在 `main` 函数中,我们首先定义了一个 `user_data` 映射,其中存储了每个用户的数据。然后,我们使用 `Encryption` 类来加密每个用户的数据,并将其保存到 `user.dat` 文件中。接下来,我们读取该文件并解密其中的数据,并将其输出到控制台。注意,我们使用的是二进制文件模式来打开文件,以确保所有字节都能正确地读取和写入。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值