AES加密算法实现

实现的类如下

import java.security.SecureRandom
import javax.crypto.spec.SecretKeySpec
import javax.crypto.{ Cipher, KeyGenerator}



/**
 * Created by neunn on 2016/5/12.
 */
class AES ( val data:Array[Byte],key:String){
  val kgen = KeyGenerator.getInstance("AES");
  val random:SecureRandom=SecureRandom.getInstance("SHA1PRNG");

  random.setSeed(key.getBytes());
  kgen.init(128, random);//密钥长度定为128位

  val secretKey = kgen.generateKey();
  val enCodeFormat = secretKey.getEncoded();
  val Key = new SecretKeySpec(enCodeFormat, "AES");
  val cipher = Cipher.getInstance("AES");// 创建密码器

  def encrypt():Array[Byte]= {
    cipher.init(Cipher.ENCRYPT_MODE, Key);// 初始化
    val result = cipher.doFinal(data);
    result; // 加密
  }
  def decrypt():Array[Byte]= {
    cipher.init(Cipher.DECRYPT_MODE, Key);// 初始化
    val result = cipher.doFinal(data);
    result; // 解密
  }
}


博主参考了这篇文章http://blog.csdn.net/hbcui1984/article/details/5201247

注意:

这里的key值不是真的密钥,而是通过以key值为参数用伪随机数生成的,同一套程序在不同系统可能或出现差异,比如博主用上诉文章的代码,在用windows给linux发送时,两个系统生成了不同的密钥,发生了:

javax.crypto.BadPaddingException: Given final block not properly padded 错误

之后修改了代码,变成了本文的代码,这个错误就解决了






  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#中的AES加密算法实现主要基于System.Security.Cryptography命名空间下的Aes类。它提供了两种模式,分别是CBC和ECB模式,其中CBC模式需要指定一个初始化向量(IV)。下面是一个简单的示例代码: ```csharp using System; using System.Security.Cryptography; using System.Text; public class AesEncryption { public static string Encrypt(string plainText, string key, string iv) { byte[] plainBytes = Encoding.UTF8.GetBytes(plainText); byte[] keyBytes = Encoding.UTF8.GetBytes(key); byte[] ivBytes = Encoding.UTF8.GetBytes(iv); using (Aes aes = Aes.Create()) { aes.Key = keyBytes; aes.IV = ivBytes; aes.Mode = CipherMode.CBC; ICryptoTransform encryptor = aes.CreateEncryptor(); byte[] encryptedBytes = encryptor.TransformFinalBlock(plainBytes, 0, plainBytes.Length); string encryptedText = Convert.ToBase64String(encryptedBytes); return encryptedText; } } public static string Decrypt(string encryptedText, string key, string iv) { byte[] encryptedBytes = Convert.FromBase64String(encryptedText); byte[] keyBytes = Encoding.UTF8.GetBytes(key); byte[] ivBytes = Encoding.UTF8.GetBytes(iv); using (Aes aes = Aes.Create()) { aes.Key = keyBytes; aes.IV = ivBytes; aes.Mode = CipherMode.CBC; ICryptoTransform decryptor = aes.CreateDecryptor(); byte[] plainBytes = decryptor.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length); string plainText = Encoding.UTF8.GetString(plainBytes); return plainText; } } } ``` 在上面的代码中,我们通过调用Create()方法来创建一个Aes对象,并设置其Key、IV和Mode属性。然后我们使用CreateEncryptor()方法创建一个加密器对象,使用TransformFinalBlock()方法进行加密操作。解密操作则是使用CreateDecryptor()方法创建一个解密器对象,同样使用TransformFinalBlock()方法进行解密操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值