加密编程怎么写

时间:2025-01-22 20:44:05 游戏攻略

加密编程可以通过多种编程语言实现,以下是几种常见语言的加密编程示例:

1. VBA加密和解密

在Excel VBA中,可以使用以下代码实现简单的加密和解密功能:

```vba

Sub 数据加密()

Dim cell As Range

Dim pwd As String

pwd = InputBox("请输入密码:") ' 获取用户输入的密码

For Each cell In Selection ' 遍历选中的单元格

If Not IsEmpty(cell) Then ' 判断单元格是否为空

cell.Value = Chr(Asc(cell.Value) + Len(pwd)) ' 加密算法

End If

Next cell

End Sub

Sub 数据解密()

Dim cell As Range

Dim pwd As String

pwd = InputBox("请输入密码:") ' 获取用户输入的密码

For Each cell In Selection ' 遍历选中的单元格

If Not IsEmpty(cell) Then ' 判断单元格是否为空

cell.Value = Chr(Asc(cell.Value) - Len(pwd)) ' 解密算法

End If

Next cell

End Sub

```

2. Python加密

在Python中,可以使用`cryptography`库进行加密和解密操作:

```python

from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes

from cryptography.hazmat.backends import default_backend

import os

def encrypt(plaintext, key):

iv = os.urandom(16)

cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())

encryptor = cipher.encryptor()

padder = padding.PKCS7(algorithms.AES.block_size).padder()

padded_data = padder.update(plaintext.encode()) + padder.finalize()

ciphertext = encryptor.update(padded_data) + encryptor.finalize()

return base64.b64encode(iv + ciphertext).decode('utf-8')

def decrypt(ciphertext, key):

decoded = base64.b64decode(ciphertext.encode())

iv = decoded[:16]

ciphertext = decoded[16:]

cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())

decryptor = cipher.decryptor()

padded_data = decryptor.update(ciphertext) + decryptor.finalize()

unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder()

plaintext = unpadder.update(padded_data) + unpadder.finalize()

return plaintext.decode()

示例

key = os.urandom(32)

plaintext = b'Hello, I am CodeHero!'

ciphertext = encrypt(plaintext, key)

print(f'Ciphertext: {ciphertext}')

decrypted_text = decrypt(ciphertext, key)

print(f'Decrypted text: {decrypted_text}')

```

3. Java加密

在Java中,可以使用`javax.crypto`包进行加密和解密操作:

```java

import javax.crypto.Cipher;

import javax.crypto.KeyGenerator;

import javax.crypto.SecretKey;

import javax.crypto.spec.SecretKeySpec;

import java.util.Base64;

public class AesEncryptionExample {

public static void main(String[] args) throws Exception {

String plainText = "Hello, World!";

// 生成AES密钥

KeyGenerator keyGen = KeyGenerator.getInstance("AES");

keyGen.init(256);

SecretKey secretKey = keyGen.generateKey();

// 加密

Cipher cipher = Cipher.getInstance("AES");

cipher.init(Cipher.ENCRYPT_MODE, secretKey);

byte[] encrypted = cipher.doFinal(plainText.getBytes());

String encryptedText = Base64.getEncoder().encodeToString(encrypted);

System.out.println("Encrypted text: " + encryptedText);

// 解密

cipher.init(Cipher.DECRYPT_MODE, secretKey);

byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(encryptedText));

String decryptedText = new String(decrypted);

System.out.println("Decrypted text: " + decryptedText);

}

}

```

4. C语言加密

在C语言