将AES加密算法从C#转换到Java并编写兼容代码。以下是一个简单的示例:
import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.util.Base64;
public class AESCrypto { private static final String ALGORITHM = "AES"; private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding"; private static final String CHARSET_NAME = "UTF-8";
private static SecretKeySpec generateKey(final String key) throws Exception {
final byte[] keyBytes = key.getBytes(CHARSET_NAME);
return new SecretKeySpec(keyBytes, ALGORITHM);
}
public static String encrypt(final String message, final String secret) throws Exception {
final Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.ENCRYPT_MODE, generateKey(secret));
final byte[] encryptedBytes = cipher.doFinal(message.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static String decrypt(final String encryptedText, final String secret) throws Exception {
final Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.DECRYPT_MODE, generateKey(secret));
final byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
return new String(decryptedBytes, StandardCharsets.UTF_8);
}
}
使用示例:
final String message = "Hello, World!"; final String secretKey = "my-secret-key";
final String encryptedMessage = AESCrypto.encrypt(message, secretKey); System.out.println("Encrypted Message: " + encryptedMessage);
final String decryptedMessage = AESCrypto.decrypt(encryptedMessage, secretKey); System.out.println("Decrypted Message: " + decryptedMessage);