java语言实现AES/ECB/PKCS5Padding加密

import android.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
public class AesUtils
{
private static final String AES_MODE = “AES/ECB/PKCS5Padding”;
private byte[] key=null;

private static byte[] generateKey() 
{      
     //结尾0等同于C++字符串结尾的\0        
     String strKey=“1234567890123450”;
     byte[] keyBytes = new byte[16];        
     keyBytes  = strKey.getBytes(StandardCharsets.UTF-8);       
      return keyBytes; 
 }   

public static String encrypt(String plainText)
 {      
    try {           
         byte[] key = generateKey();            
         byte[] plainBytes = plainText.getBytes(StandardCharsets.UTF_8);            
         SecretKeySpec keySpec = new SecretKeySpec(key, "AES");            
         Cipher cipher = Cipher.getInstance(AES_MODE);           
         cipher.init(Cipher.ENCRYPT_MODE, keySpec);                    
          byte[] encrypted = cipher.doFinal(padded);                 
          return Base64.encodeToString(encrypted,Base64.NO_WRAP);       
         } catch (Exception e) {          
          throw new RuntimeException("AES加密失败", e);        }  
  }   

  public static String decrypt(String base64Cipher) {      
try {          
         byte[] key = generateKey();            
         byte[] encrypted = Base64.decode(base64Cipher,Base64.NO_WRAP);            
         SecretKeySpec keySpec = new SecretKeySpec(key, "AES");            
         Cipher cipher = Cipher.getInstance(AES_MODE);           
         cipher.init(Cipher.DECRYPT_MODE, keySpec);             
         byte[] decrypted = cipher.doFinal(encrypted);             
         return new String(decrypted,StandardCharsets.UTF_8);      
         } catch (Exception e) {           
          throw new RuntimeException("AES解密失败", e);       
         }
   }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值