c++ 关于sha1算法

Rossoneri 2013-11-12 08:46:44
找了很多的c++实现sha1的算法,为什么算出来的和php里面标准的的sha1()函数得到的结果不一样呢?

哪位大牛给个解释啊
...全文
377 7 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
unituniverse2 2013-11-13
  • 打赏
  • 举报
回复
至少其中之一必有问题。。结论和具体算法无关的。有关的话就错了
ken_scott 2013-11-13
  • 打赏
  • 举报
回复
把二者的结果给出来,让大家看看啊
赵4老师 2013-11-13
  • 打赏
  • 举报
回复
#pragma comment(lib, "crypt32.lib")
#pragma comment(lib, "advapi32.lib")
#define _WIN32_WINNT 0x0400
#include <stdio.h>
#include <windows.h>
#include <wincrypt.h>
#define MY_ENCODING_TYPE  (PKCS_7_ASN_ENCODING | X509_ASN_ENCODING)
#define KEYLENGTH  0x00800000
void HandleError(char *s);
//--------------------------------------------------------------------
//  These additional #define statements are required.
#define ENCRYPT_ALGORITHM CALG_RC4
#define ENCRYPT_BLOCK_SIZE 8
//   Declare the function EncryptFile. The function definition
//   follows main.
BOOL EncryptFile(
    PCHAR szSource,
    PCHAR szDestination,
    PCHAR szPassword);
//--------------------------------------------------------------------
//   Begin main.
void main(void) {
    CHAR szSource[100];
    CHAR szDestination[100];
    CHAR szPassword[100];
    printf("Encrypt a file. \n\n");
    printf("Enter the name of the file to be encrypted: ");
    scanf("%s",szSource);
    printf("Enter the name of the output file: ");
    scanf("%s",szDestination);
    printf("Enter the password:");
    scanf("%s",szPassword);
    //--------------------------------------------------------------------
    // Call EncryptFile to do the actual encryption.
    if(EncryptFile(szSource, szDestination, szPassword)) {
        printf("Encryption of the file %s was a success. \n", szSource);
        printf("The encrypted data is in file %s.\n",szDestination);
    } else {
        HandleError("Error encrypting file!");
    }
} // End of main
//--------------------------------------------------------------------
//   Code for the function EncryptFile called by main.
static BOOL EncryptFile(
    PCHAR szSource,
    PCHAR szDestination,
    PCHAR szPassword)
//--------------------------------------------------------------------
//   Parameters passed are:
//     szSource, the name of the input, a plaintext file.
//     szDestination, the name of the output, an encrypted file to be
//         created.
//     szPassword, the password.
{
    //--------------------------------------------------------------------
    //   Declare and initialize local variables.
    FILE *hSource;
    FILE *hDestination;
    HCRYPTPROV hCryptProv;
    HCRYPTKEY hKey;
    HCRYPTHASH hHash;
    PBYTE pbBuffer;
    DWORD dwBlockLen;
    DWORD dwBufferLen;
    DWORD dwCount;
    //--------------------------------------------------------------------
    // Open source file.
    if(hSource = fopen(szSource,"rb")) {
        printf("The source plaintext file, %s, is open. \n", szSource);
    } else {
        HandleError("Error opening source plaintext file!");
    }
    //--------------------------------------------------------------------
    // Open destination file.
    if(hDestination = fopen(szDestination,"wb")) {
        printf("Destination file %s is open. \n", szDestination);
    } else {
        HandleError("Error opening destination ciphertext file!");
    }
    //以下获得一个CSP句柄
    if(CryptAcquireContext(
                &hCryptProv,
                NULL,               //NULL表示使用默认密钥容器,默认密钥容器名
                //为用户登陆名
                NULL,
                PROV_RSA_FULL,
                0)) {
        printf("A cryptographic provider has been acquired. \n");
    } else {
        if(CryptAcquireContext(
                    &hCryptProv,
                    NULL,
                    NULL,
                    PROV_RSA_FULL,
                    CRYPT_NEWKEYSET))//创建密钥容器
        {
            //创建密钥容器成功,并得到CSP句柄
            printf("A new key container has been created.\n");
        } else {
            HandleError("Could not create a new key container.\n");
        }
    }
    //--------------------------------------------------------------------
    // 创建一个会话密钥(session key)
    // 会话密钥也叫对称密钥,用于对称加密算法。
    // (注: 一个Session是指从调用函数CryptAcquireContext到调用函数
    //   CryptReleaseContext 期间的阶段。会话密钥只能存在于一个会话过程)
    //--------------------------------------------------------------------
    // Create a hash object.
    if(CryptCreateHash(
                hCryptProv,
                CALG_MD5,
                0,
                0,
                &hHash)) {
        printf("A hash object has been created. \n");
    } else {
        HandleError("Error during CryptCreateHash!\n");
    }
    //--------------------------------------------------------------------
    // 用输入的密码产生一个散列
    if(CryptHashData(
                hHash,
                (BYTE *)szPassword,
                strlen(szPassword),
                0)) {
        printf("The password has been added to the hash. \n");
    } else {
        HandleError("Error during CryptHashData. \n");
    }
    //--------------------------------------------------------------------
    // 通过散列生成会话密钥
    if(CryptDeriveKey(
                hCryptProv,
                ENCRYPT_ALGORITHM,
                hHash,
                KEYLENGTH,
                &hKey)) {
        printf("An encryption key is derived from the password hash. \n");
    } else {
        HandleError("Error during CryptDeriveKey!\n");
    }
    //--------------------------------------------------------------------
    // Destroy the hash object.
    CryptDestroyHash(hHash);
    hHash = NULL;
    //--------------------------------------------------------------------
    //  The session key is now ready.
    //--------------------------------------------------------------------
    // 因为加密算法是按ENCRYPT_BLOCK_SIZE 大小的块加密的,所以被加密的
    // 数据长度必须是ENCRYPT_BLOCK_SIZE 的整数倍。下面计算一次加密的
    // 数据长度。
    dwBlockLen = 1000 - 1000 % ENCRYPT_BLOCK_SIZE;
    //--------------------------------------------------------------------
    // Determine the block size. If a block cipher is used,
    // it must have room for an extra block.
    if(ENCRYPT_BLOCK_SIZE > 1)
        dwBufferLen = dwBlockLen + ENCRYPT_BLOCK_SIZE;
    else
        dwBufferLen = dwBlockLen;
    //--------------------------------------------------------------------
    // Allocate memory.
    if(pbBuffer = (BYTE *)malloc(dwBufferLen)) {
        printf("Memory has been allocated for the buffer. \n");
    } else {
        HandleError("Out of memory. \n");
    }
    //--------------------------------------------------------------------
    // In a do loop, encrypt the source file and write to the source file.
    do {
        //--------------------------------------------------------------------
        // Read up to dwBlockLen bytes from the source file.
        dwCount = fread(pbBuffer, 1, dwBlockLen, hSource);
        if(ferror(hSource)) {
            HandleError("Error reading plaintext!\n");
        }
        //--------------------------------------------------------------------
        // 加密数据
        if(!CryptEncrypt(
                    hKey,           //密钥
                    0,              //如果数据同时进行散列和加密,这里传入一个
                    //散列对象
                    feof(hSource),  //如果是最后一个被加密的块,输入TRUE.如果不是输.
                    //入FALSE这里通过判断是否到文件尾来决定是否为
                    //最后一块。
                    0,              //保留
                    pbBuffer,       //输入被加密数据,输出加密后的数据
                    &dwCount,       //输入被加密数据实际长度,输出加密后数据长度
                    dwBufferLen))   //pbBuffer的大小。
        {
            HandleError("Error during CryptEncrypt. \n");
        }
        //--------------------------------------------------------------------
        // Write data to the destination file.
        fwrite(pbBuffer, 1, dwCount, hDestination);
        if(ferror(hDestination)) {
            HandleError("Error writing ciphertext.");
        }
    } while(!feof(hSource));
    //--------------------------------------------------------------------
    //  End the do loop when the last block of the source file has been
    //  read, encrypted, and written to the destination file.
    //--------------------------------------------------------------------
    // Close files.
    if(hSource)
        fclose(hSource);
    if(hDestination)
        fclose(hDestination);
    //--------------------------------------------------------------------
    // Free memory.
    if(pbBuffer)
        free(pbBuffer);
    //--------------------------------------------------------------------
    // Destroy session key.
    if(hKey)
        CryptDestroyKey(hKey);
    //--------------------------------------------------------------------
    // Destroy hash object.
    if(hHash)
        CryptDestroyHash(hHash);
    //--------------------------------------------------------------------
    // Release provider handle.
    if(hCryptProv)
        CryptReleaseContext(hCryptProv, 0);
    return(TRUE);
} // End of Encryptfile
//--------------------------------------------------------------------
//  This example uses the function HandleError, a simple error
//  handling function, to print an error message to the standard error
//  (stderr) file and exit the program.
//  For most applications, replace this function with one
//  that does more extensive error reporting.
void HandleError(char *s) {
    fprintf(stderr,"An error occurred in running the program. \n");
    fprintf(stderr,"%s\n",s);
    fprintf(stderr, "Error number %x.\n", GetLastError());
    fprintf(stderr, "Program terminating. \n");
    exit(1);
} // End of HandleError

赵4老师 2013-11-13
  • 打赏
  • 举报
回复
#pragma comment(lib, "crypt32.lib")
#pragma comment(lib, "advapi32.lib")
#define _WIN32_WINNT 0x0400
#include <windows.h>
#include <wincrypt.h>
#include <tchar.h>
#include <stdio.h>
#include <stdlib.h>
void HandleError(TCHAR* s);
void Wait(TCHAR* s);
int _tmain(int argc, _TCHAR* argv[]) {
    HCRYPTPROV hProv;
    LPTSTR pszName;
    DWORD dwType;
    DWORD cbName;
    DWORD dwIndex = 0;
    BYTE* ptr;
    ALG_ID aiAlgid;
    DWORD dwBits;
    DWORD dwNameLen;
    CHAR szName[100];
    BYTE pbData[1024];
    DWORD cbData = 1024;
    DWORD dwIncrement = sizeof(DWORD);
    DWORD dwFlags = CRYPT_FIRST;
    DWORD dwParam = PP_CLIENT_HWND;
    CHAR* pszAlgType = NULL;
    BOOL fMore = TRUE;
    printf("列举可用的CSP提供者类型\n");
    printf("CSP提供者类型  CSP提供者类型名称\n");
    _tprintf(TEXT("_____________  __________________________________________________\n"));
    //循环调用CryptEnumProviderType函数枚举当前计算机支持的CSP类型
    while(CryptEnumProviderTypes(dwIndex, NULL, 0,
                                 &dwType,
                                 NULL, //第一次调用设置为NULL
                                 &cbName)) //将要输出的pszName的长度
    {
        //为pszName分配内存
        if(!(pszName = (LPTSTR)LocalAlloc(LMEM_ZEROINIT, cbName))) {
            HandleError(TEXT("调用LocalAlloc分配内存出错\n"));
        }
        //获取CSP提供者类型名
        if(CryptEnumProviderTypes(dwIndex++, NULL, 0,
                                  &dwType, pszName, &cbName)) {
            _tprintf(TEXT("%13d  %s\n"), dwType, pszName);
        } else {
            HandleError(TEXT("调用CryptEnumProviderTypes出错\n"));
        }
        LocalFree(pszName);
    }
    //连接CSP,创建CSP句柄
    if(!CryptAcquireContext(&hProv, NULL, NULL,
                            PROV_RSA_FULL, NULL)) {
        HandleError(TEXT("调用CryptAcquireContext函数出错\n"));
    }
    //获得CSP参数,枚举支持的密码算法
    printf("\n枚举支持的密码算法\n");
    printf("算法ID     位数  类型  长度  算法名称\n");
    printf("_________  ____  ____  ____  ____________________\n");
    while(fMore) {
        if(CryptGetProvParam(hProv, PP_ENUMALGS, pbData,
                             &cbData, dwFlags)) {
            //从pbData缓冲区中解析出算法信息
            dwFlags = 0;
            ptr = pbData;
            aiAlgid = *(ALG_ID*)ptr;
            ptr += sizeof(ALG_ID);
            dwBits = *(DWORD*)ptr;
            ptr += dwIncrement;
            dwNameLen = *(DWORD*)ptr;
            ptr += dwIncrement;
            strncpy(szName, (char*)ptr, __min(dwNameLen,99));szName[__min(dwNameLen,99)]=0;
            //获取算法类型
            switch(GET_ALG_CLASS(aiAlgid)) {
            case ALG_CLASS_DATA_ENCRYPT:
                pszAlgType = "加密";
                break;
            case ALG_CLASS_HASH:
                pszAlgType = "哈希";
                break;
            case ALG_CLASS_KEY_EXCHANGE:
                pszAlgType = "交换";
                break;
            case ALG_CLASS_SIGNATURE:
                pszAlgType = "签名";
                break;
            default:
                pszAlgType = "未知";
                break;
            }
            //打印算法信息
            printf("%8.8xh  %4d  %4s  %4d  %s\n",
                   aiAlgid, dwBits, pszAlgType, dwNameLen, szName);
        } else {
            fMore = FALSE;
        }
    }
    Wait(TEXT("\n按Enter继续"));
    if(!(CryptReleaseContext(hProv, 0))) {
        HandleError(TEXT("调用CryptReleaseContext时出错\n"));
    }
    if(GetLastError() == ERROR_NO_MORE_ITEMS) {
        _tprintf(TEXT("\n程序成功执行完毕\n"));
    } else {
        HandleError(TEXT("读取算法信息时出错"));
    }
    return 0;
}
void HandleError(TCHAR* s) {
    _tprintf(TEXT("程序运行出现错误.\n"));
    _tprintf(TEXT("%s\n"),s);
    _tprintf(TEXT("错误代码%x\n."), GetLastError());
    _tprintf(TEXT("程序终止.\n"));
    exit(1);
}
void Wait(TCHAR* s) {
    char x;
    _tprintf(s);
    x = getchar();
}
//列举可用的CSP提供者类型
//CSP提供者类型  CSP提供者类型名称
//_____________  __________________________________________________
//            1  RSA Full (Signature and Key Exchange)
//            3  DSS Signature
//           12  RSA SChannel
//           13  DSS Signature with Diffie-Hellman Key Exchange
//           18  Diffie-Hellman SChannel
//           24  RSA Full and AES
//
//枚举支持的密码算法
//算法ID     位数  类型  长度  算法名称
//_________  ____  ____  ____  ____________________
//00006602h   128  加密     4  RC2
//00006801h   128  加密     4  RC4
//00006601h    56  加密     4  DES
//00006609h   112  加密    13  3DES TWO KEY
//00006603h   168  加密     5  3DES
//00008004h   160  哈希     6  SHA-1
//00008001h   128  哈希     4  MD2
//00008002h   128  哈希     4  MD4
//00008003h   128  哈希     4  MD5
//00008008h   288  哈希    12  SSL3 SHAMD5
//00008005h     0  哈希     4  MAC
//00002400h  1024  签名     9  RSA_SIGN
//0000a400h  1024  交换     9  RSA_KEYX
//00008009h     0  哈希     5  HMAC
//
//按Enter继续
//
//程序成功执行完毕
//
Adol1111 2013-11-12
  • 打赏
  • 举报
回复
例子呢?代码呢?没代码谁知道为什么?应该是实现不一样,生成的sha1有点小区别吧。
turing-complete 2013-11-12
  • 打赏
  • 举报
回复
实现采用了不同的算法呗
dyw 2013-11-12
  • 打赏
  • 举报
回复
给个不一样的例子

65,189

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧