aes-cbc-128加密C#、java和php代码实现

php

$method = 'aes-128-cbc';
$key = '1234567890123456';
$iv = '1234567890123456';
$data = '你好啊';
$encrypted = openssl_encrypt($data, $method, $key, 1, $iv);
$encrypted = base64_encode($encrypted);//结果和C#加密的一样
echo $encrypted;
echo "
"
; $decrypted = openssl_decrypt(base64_decode($encrypted), $method, $key, 1, $iv); echo $decrypted;

aes-cbc-128加密C#、java和php代码实现_第1张图片

C#

新建.net7控制台项目

internal class Program
{
    static void Main(string[] args)
    {
        var key = "1234567890123456";
        var iv = "1234567890123456";
        var input = "你好啊";
        var jiami = EncryptByAESNew(input, key, iv);
        Console.WriteLine(jiami);
        Console.WriteLine(DecryptByAESNew(jiami, key, iv));
    }

    /// 
    /// AES加密算法
    /// 
    /// 明文字符串
    /// 密钥 长度为:16
    /// 偏移 长度为:16
    /// 字符串
    public static string EncryptByAESNew(string input, string key, string iv)
    {
        if (string.IsNullOrWhiteSpace(input))
        {
            return input;
        }
        using (var rijndaelManaged = Aes.Create())
        {
            rijndaelManaged.Mode = CipherMode.CBC;
            rijndaelManaged.Padding = PaddingMode.PKCS7;
            rijndaelManaged.FeedbackSize = 128;
            rijndaelManaged.Key = Encoding.UTF8.GetBytes(key);
            rijndaelManaged.IV = Encoding.UTF8.GetBytes(iv);
            ICryptoTransform encryptor = rijndaelManaged.CreateEncryptor(rijndaelManaged.Key, rijndaelManaged.IV);
            using (MemoryStream msEncrypt = new MemoryStream())
            {
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                    {
                        swEncrypt.Write(input);
                    }
                    byte[] bytes = msEncrypt.ToArray();
                    return Convert.ToBase64String(bytes);
                }
            }
        }
    }

    ///   
        /// AES解密  
        /// 
        /// 密文字节数组
    /// 密钥 长度为:16、24、32
    /// 偏移 长度为:16
        /// 返回解密后的字符串  
        public static string DecryptByAESNew(string input, string key, string iv)
    {
        if (string.IsNullOrWhiteSpace(input))
        {
            return input;
        }
        var buffer = Convert.FromBase64String(input);
        //buffer = hexStringToByteArray(input);//如果是hex则用hex方式处理
        using (var rijndaelManaged = Aes.Create())
        {
            rijndaelManaged.Mode = CipherMode.CBC;
            rijndaelManaged.Padding = PaddingMode.PKCS7;
            rijndaelManaged.FeedbackSize = 128;
            rijndaelManaged.Key = Encoding.UTF8.GetBytes(key);
            rijndaelManaged.IV = Encoding.UTF8.GetBytes(iv);
            ICryptoTransform decryptor = rijndaelManaged.CreateDecryptor(rijndaelManaged.Key, rijndaelManaged.IV);
            using (MemoryStream msEncrypt = new MemoryStream(buffer))
            {
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, decryptor, CryptoStreamMode.Read))
                {
                    using (StreamReader srEncrypt = new StreamReader(csEncrypt))
                    {
                        return srEncrypt.ReadToEnd();
                    }
                }
            }
        }
    }
}

aes-cbc-128加密C#、java和php代码实现_第2张图片

java

新建maven项目,增加BouncyCastle包

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0modelVersion>

	<groupId>com.wujialianggroupId>
	<artifactId>test10artifactId>
	<version>0.0.1-SNAPSHOTversion>
	<packaging>jarpackaging>

	<name>test10name>
	<url>http://maven.apache.orgurl>

	<properties>
		<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
		<maven.compiler.source>1.8maven.compiler.source>
		<maven.compiler.target>1.8maven.compiler.target>
	properties>

	<dependencies>
		<dependency>
			<groupId>junitgroupId>
			<artifactId>junitartifactId>
			<version>3.8.1version>
			<scope>testscope>
		dependency>
		<dependency>
			<groupId>org.bouncycastlegroupId>
			<artifactId>bcprov-jdk15onartifactId>
			<version>1.56version>
		dependency>
	dependencies>
project>

app.java

package com.wujialiang.test10;

import java.security.Security;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

/**
 * Hello world!
 *
 */
public class App 
{
	static {
		// add new bouncy castle ciphers
		Security.addProvider(new BouncyCastleProvider());
	}
	
    public static void main( String[] args )
    {
    	String key = "1234567890123456";
    	String iv = "1234567890123456";
    	String input = "你好啊";
    	String jiami = encrypt(input, key, iv);
    	System.out.println(jiami);
    	System.out.println(decrypt(jiami, key, iv));
    }
    
    /**
     * AES解密
     * @param plaintext
     * @param key
     * @param iv
     * @return
     */
    public static String encrypt(String plaintext, String key, String iv) {
        try {
            SecretKeySpec keySpec = new SecretKeySpec(key.getBytes("utf-8"), "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes("utf-8"));
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
            byte[] encrypted = cipher.doFinal(plaintext.getBytes("utf-8"));
            return Base64.getEncoder().encodeToString(encrypted);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    /**
     * AES加密
     * @param ciphertext
     * @param key
     * @param iv
     * @return
     */
    public static String decrypt(String ciphertext, String key, String iv) {
        try {
            SecretKey keySpec = new SecretKeySpec(key.getBytes("utf-8"), "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes("utf-8"));
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
            byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(ciphertext));
            return new String(decrypted, "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

aes-cbc-128加密C#、java和php代码实现_第3张图片

你可能感兴趣的:(php,dotnet,java,c#,java,php)