最近在项目中写了一种异或混合加密算法,特此记录便于日后查阅。
#include "com_openailab_oascloud_security_jni_eaidk_EaidkAuthJNI.h"
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <stdlib.h>
#include <sys/time.h>
//正向扰动
int reoder(uint8_t *src, uint8_t *dst, int len) {
int i;
int m = 0;
int n = len - 1;
for (i = 0; i < len; i++) {
if (i % 3 == 0) {
dst[m++] = src[i];
} else {
dst[n--] = src[i];
}
}
return 0;
}
//反向扰动
int recover(uint8_t *src, uint8_t *dst, int len) {
int i;
int m = 0;
int n = len - 1;
for (i = 0; i < len; i++) {
if (i % 3 == 0) {
dst[i] = src[m++];
} else {
dst[i] = src[n--];
}
}
return 0;
}
//异或混合加密算法
int mixEncrypt(
const unsigned char* plaintext,
unsigned int plaintext_size,
unsigned char *ciphertext,
size_t *ciphertext_size)
{
struct timeval time;
gettimeofday(&time, NULL);
// microsecond has 1 000 000
// Assuming you did not need quite that accuracy
// Also do not assume the system clock has that accuracy.
srand((time.tv_sec * 1000) + (time.tv_usec / 1000));
if ((plaintext_size < 128) && (!(plaintext_size & 3))) {
int i, j;
for (i = 0; i < (int)(128 - plaintext_size); i += 4) {
long rdm = random();
ciphertext[i + 0] = (rdm >> 24) & 0xff;
ciphertext[i + 1] = (rdm >> 16) & 0xff;
ciphertext[i + 2] = (rdm >> 8) & 0xff;
ciphertext[i + 3] = (rdm)& 0xff;
}
for (i = 128 - plaintext_size, j = 0; i < 128; ++i, ++j) {
ciphertext[i] = plaintext[j] ^ ciphertext[j];
}
}
else {
return -1;
}
*ciphertext_size = 128;
return 0;
}
//异或混合解密算法
int fake_rsa_decrypt(
const unsigned char *ciphertext,
unsigned char *plaintext,
size_t *plaintext_size) {
*plaintext_size = 64;
if (((*plaintext_size) < 128) && (!((*plaintext_size) & 3))) {
int i;
for (i = 0; i < (int) (*plaintext_size); i++) {
plaintext[i] = ciphertext[128 - (*plaintext_size) + i] ^ ciphertext[i];
}
} else {
return -1;
}
return 0;
}
到此C语言异或混合通用加密算法介绍完成。