Java AES Encrypt aesEncrypt(String content, String encryptKey)

Here you can find the source of aesEncrypt(String content, String encryptKey)

Description

aes Encrypt

License

Open Source License

Declaration

public static String aesEncrypt(String content, String encryptKey) 

Method Source Code

//package com.java2s;
/*//from ww  w. j  av a2  s  .c  o  m
 * Project Name: zc-collect-common
 * File Name: EncryptUtil.java
 * Class Name: EncryptUtil
 *
 * Copyright 2014 Hengtian Software Inc
 *
 * Licensed under the Hengtiansoft
 *
 * http://www.hengtiansoft.com
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
 * implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;

public class Main {

    public static String aesEncrypt(String content, String encryptKey) {
        return parseByte2HexStr(aesEncryptToBytes(content, encryptKey));
    }

    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    public static byte[] aesEncryptToBytes(String content, String encryptKey) {
        KeyGenerator kgen;
        try {
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            random.setSeed(encryptKey.getBytes());
            kgen = KeyGenerator.getInstance("AES");
            kgen.init(128, random);
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES"));
            return cipher.doFinal(content.getBytes("utf-8"));
        } catch (Exception e) {
        }
        return null;
    }
}

Related

  1. aesEncrypt(byte[] source, Key key)
  2. aesEncrypt(String content, String key)
  3. aesEncryptBytes(byte[] pBytes, SecretKeySpec pKeySpec, IvParameterSpec ivParameterSpec)
  4. aesEncryptToBytes(String content, String encryptKey)