各处哈希函数SHA-1的具体代码
时间: 2024-02-28 07:57:21 浏览: 17
SHA-1的代码实现存在于各种编程语言的库中,以下是一些常见编程语言中的SHA-1实现代码示例:
1. Java:
```java
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.nio.charset.StandardCharsets;
public class SHA1 {
public static String sha1(String input) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] hash = md.digest(input.getBytes(StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
for (byte b : hash) {
sb.append(String.format("%02x", b));
}
return sb.toString();
}
}
```
2. Python:
```python
import hashlib
def sha1(input):
hash_object = hashlib.sha1(input.encode())
hex_dig = hash_object.hexdigest()
return hex_dig
```
3. C++:
```c++
#include <iostream>
#include <fstream>
#include <sstream>
#include <cstring>
#include <openssl/sha.h>
std::string sha1(const std::string& input) {
unsigned char digest[SHA_DIGEST_LENGTH];
SHA1(reinterpret_cast<const unsigned char*>(input.c_str()), input.length(), digest);
std::stringstream ss;
for(int i = 0; i < SHA_DIGEST_LENGTH; i++) {
ss << std::hex << static_cast<int>(digest[i]);
}
return ss.str();
}
```
以上是SHA-1在Java、Python和C++中的实现代码示例,其他编程语言中的SHA-1实现也类似,可根据具体语言和库的文档进行使用。