的代码示例。在下面的代码示例中,我们将演示如何使用 AES-256 加密算法在 C 和 Java 之间进行加密。
C 代码示例:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/aes.h>
#define AES_BLOCK_SIZE 16
int main(int argc, char *argv[]) {
unsigned char key[AES_BLOCK_SIZE] = "0123456789abcdef";
unsigned char iv[AES_BLOCK_SIZE] = "fedcba9876543210";
AES_KEY aesKey;
AES_set_encrypt_key(key, AES_BLOCK_SIZE * 8, &aesKey);
char plaintext[] = "This is a secret message";
int plaintext_len = strlen(plaintext);
int ciphertext_len = ((plaintext_len + AES_BLOCK_SIZE - 1) / AES_BLOCK_SIZE) * AES_BLOCK_SIZE;
unsigned char ciphertext[ciphertext_len];
AES_cbc_encrypt((unsigned char*)plaintext, ciphertext, plaintext_len, &aesKey, iv, AES_ENCRYPT);
printf("Ciphertext: ");
for(int i = 0; i < ciphertext_len; i++) {
printf("%02x", ciphertext[i]);
}
printf("
");
return 0;
}
Java 代码示例:
import java.security.Key;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class AesCbcExample {
private static final String ALGO_NAME = "AES";
private static final int KEY_SIZE = 256;
private static final int BLOCK_SIZE = 16;
public static void main(String[] args) throws Exception {
byte[] key = "0123456789abcdef".getBytes();
byte[] iv = "fedcba9876543210".getBytes();
SecretKeySpec keySpec = new SecretKeySpec(key, ALGO_NAME);
Cipher cipher = Cipher.getInstance(ALGO_NAME);
SecureRandom secureRandom = new SecureRandom();
secureRandom.nextBytes(iv);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, secureRandom);
String plainText = "This is a secret message";
byte[] plainTextBytes = plainText.getBytes();
int plainTextLen = plainTextBytes.length;
int cipherTextLen = ((plainTextLen + BLOCK_SIZE) / BLOCK_SIZE) * BLOCK_SIZE;
byte[] cipherText = new byte[cipherTextLen];
cipher.doFinal(plainTextBytes, 0, plainTextLen, cipherText, 0);
System.out.println("Ciphertext: ");
for (int i = 0; i < cipherText.length; i++) {
System.out.print(Integer.toHexString(cipherText[i] & 0xFF) + " ");
}
System.out.println();
}
}
这两个示例都使用了 AES-256 算法,并提供了密钥和初始化向量 (IV) 的不同实现。在 C 示例中,我们使用了 OpenSSL 的 AES 函数库,而在 Java 示例中,我们使用了 Java 提供的 javax.crypto.Cipher 类。两者都可以通过设置相应的参数来进行加密和解密操作。
领取专属 10元无门槛券
手把手带您无忧上云