欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java实现的AES加密算法完整实例

程序员文章站 2024-03-13 13:50:09
本文实例讲述了java实现的aes加密算法。分享给大家供大家参考,具体如下: import javax.crypto.cipher; import javax....

本文实例讲述了java实现的aes加密算法。分享给大家供大家参考,具体如下:

import javax.crypto.cipher;
import javax.crypto.spec.ivparameterspec;
import javax.crypto.spec.secretkeyspec;
import android.util.base64;
/**
 * @author vipin.cb , vipin.cb@experionglobal.com <br>
 *     sep 27, 2013, 5:18:34 pm <br>
 *     package:- <b>com.veebow.util</b> <br>
 *     project:- <b>veebow</b>
 *     <p>
 */
public class aescrypt {
  private final cipher cipher;
  private final secretkeyspec key;
  private algorithmparameterspec spec;
  public static final string seed_16_character = "u1mju1m0fdouz.qz";
  public aescrypt() throws exception {
    // hash password with sha-256 and crop the output to 128-bit for key
    messagedigest digest = messagedigest.getinstance("sha-256");
    digest.update(seed_16_character.getbytes("utf-8"));
    byte[] keybytes = new byte[32];
    system.arraycopy(digest.digest(), 0, keybytes, 0, keybytes.length);
    cipher = cipher.getinstance("aes/cbc/pkcs7padding");
    key = new secretkeyspec(keybytes, "aes");
    spec = getiv();
  }
  public algorithmparameterspec getiv() {
    byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, };
    ivparameterspec ivparameterspec;
    ivparameterspec = new ivparameterspec(iv);
    return ivparameterspec;
  }
  public string encrypt(string plaintext) throws exception {
    cipher.init(cipher.encrypt_mode, key, spec);
    byte[] encrypted = cipher.dofinal(plaintext.getbytes("utf-8"));
    string encryptedtext = new string(base64.encode(encrypted,
        base64.default), "utf-8");
    return encryptedtext;
  }
  public string decrypt(string cryptedtext) throws exception {
    cipher.init(cipher.decrypt_mode, key, spec);
    byte[] bytes = base64.decode(cryptedtext, base64.default);
    byte[] decrypted = cipher.dofinal(bytes);
    string decryptedtext = new string(decrypted, "utf-8");
    return decryptedtext;
  }
}

ps:关于加密解密感兴趣的朋友还可以参考本站在线工具:

密码安全性在线检测:

高强度密码生成器:
http://tools.jb51.net/password/createstrongpassword

md5在线加密工具:
http://tools.jb51.net/password/createmd5password

迅雷、快车、旋风url加密/解密工具:

在线散列/哈希算法加密工具:

希望本文所述对大家java程序设计有所帮助。