用Blowfish加密和解密消息 [英] Encrypting and decrypting a message with Blowfish

查看:212
本文介绍了用Blowfish加密和解密消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是加密和解密消息的基本代码:

Here is a basic code of encryping and decrypting a message:

#include <stdio.h>
#include <openssl/blowfish.h>
#include <string.h>

//gcc cryptage.c -o cryptage -lcrypto

int main(){

BF_KEY *key = malloc(sizeof(BF_KEY));

unsigned char *crypt_key = "Key of encryption";
const unsigned char *in = "Message to encrypt";
int len = strlen(crypt_key);
unsigned char *out = malloc(sizeof(char)*len);
unsigned char *result = malloc(sizeof(char)*len);


//Defining encryption key
BF_set_key(key, len, crypt_key);

//Encryption
BF_ecb_encrypt(in, out, key, BF_ENCRYPT);

//Décryption
BF_ecb_encrypt(out, result, key, BF_DECRYPT);

fprintf(stdout,"Result: %s\n",result);

return 0;

}

我的问题是我得到的结果。它总是一个8个字符的字符串,没有更多。
你能帮我加密和解密完整的信息吗?

My problem is the result i get. It's always a String of 8 caracters, no more. Can you please help me encrypt and decrypt the full message?

谢谢!

推荐答案

as @WhozCraig说,一次做8个字节。

As @WhozCraig says, do things 8 bytes at a time.

要加密的数据应该被视为一个字节数组,而不是一个C字符串。

请考虑使用 \0 加密的字符串,并填充随机数据以形成字节数组是8的倍数。

多次调用加密,每次迭代加密8个字节。

The data to encrypt should be viewed as a byte array and not a C string.
So consider the string to encrypt with the \0 and padded with random data to form a byte array that is a multiple of 8.
Call encrypt multiple times, encrypting 8 bytes per iteration.

要解密,请同时呼叫解密的迭代。请注意,结果缓冲区可能需要调整为8的倍数。

To decrypt, call decryption the same number of iterations. Note that the result buffer may need to be sized up to a multiple of 8.

const unsigned char *in = "Message to encrypt";
size_t InSize = strlen(in) + 1;
int KeyLen = strlen(crypt_key);
size_t OutSize = (InSize + 7) & (~7);
unsigned char *out = malloc(Outsize);
unsigned char *outnext = out;
//Defining encryption key
BF_set_key(key, KeyLen, crypt_key);

//Encryption
while (InSize >= 8) {    
  BF_ecb_encrypt(in, outnext, key, BF_ENCRYPT);
  in += 8;
  outnext += 8;
  InSize -= 8;
}
if (Insize > 0) {  // Cope with non-octal length
  unsigned char buf8[8];
  memcpy(buf8, in, InSize);
  for (i=InSize; i<8; i++) {
    buf8[i] = rand();
  }  
  BF_ecb_encrypt(buf8, outnext, key, BF_ENCRYPT);
}

//Décryption
unsigned char *result = malloc(OutSize);
unsigned char *resultNext = result;
while (OutSize) {
  BF_ecb_encrypt(out, resultNext, key, BF_DECRYPT);
  out += 8;
  resultNext += 8;
  OutSize -= 8;
}

fprintf(stdout,"Result: %s\n",result);
// No need to print the random bytes that were generated.
return 0;
}

不太舒服有一个已知字节( \ 0 )编码在最后一个块。不同的长度指示可能是谨慎的。

Not quite comfortable have a known byte (\0) encoded in the last block. A different length indication may be prudent.

这篇关于用Blowfish加密和解密消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆