netcore AES同等效轉java語言 加密方法

爱吃糖的宝宝發表於2024-03-06

private static byte[] Keys = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F };
/// <summary>
/// DES加密字串
/// </summary>
/// <param name="encryptString">待加密的字串</param>
/// <param name="encryptKey">加密金鑰,要求為16位</param>
/// <returns>加密成功返回加密後的字串,失敗返回源串</returns>

public static string EncryptDES(this string encryptString, string encryptKey)
{
try
{
byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 16));
byte[] rgbIV = Keys;
byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);

using (var DCSP = Aes.Create())
{
using (MemoryStream mStream = new MemoryStream())
{
using (CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write))
{
cStream.Write(inputByteArray, 0, inputByteArray.Length);
cStream.FlushFinalBlock();
return Convert.ToBase64String(mStream.ToArray()).Replace('+', '_').Replace('/', '~');
}
}
}
}
catch (Exception ex)
{
throw new Exception("密碼加密異常" + ex.Message);
}

}


——————java程式碼——

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class EncryptionUtils {

public static String encryptDES(String encryptString, String encryptKey) {
try {
String decryptKey = "A7ABA9E202D94C43A3CA66002BF77188";
byte[] rgbKey = encryptKey.substring(0, 16).getBytes(StandardCharsets.UTF_8);
byte[] rgbIV ={ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F };
byte[] inputByteArray = encryptString.getBytes(StandardCharsets.UTF_8);

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec keySpec = new SecretKeySpec(rgbKey, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(rgbIV);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);

byte[] encryptedBytes = cipher.doFinal(inputByteArray);

String base64Encoded = Base64.getEncoder().encodeToString(encryptedBytes);
return base64Encoded.replace('+', '_').replace('/', '~');
} catch (Exception ex) {
throw new RuntimeException("密碼加密異常: " + ex.getMessage());
}
}



public static void main(String[] args) {
String encryptKey = "your_encrypt_key";
String encryptString = "string_to_encrypt";
String encryptedString = encryptDES(encryptString, encryptKey);
System.out.println("Encrypted String: " + encryptedString);
}
}

相關文章