netcore AES同等效转java语言 加密方法

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);
    }
}
posted @ 2024-03-06 20:22  爱吃糖的宝宝  阅读(9)  评论(0编辑  收藏  举报