0

代码:


import org.apache.commons.codec.binary.Base64;

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.util.Arrays;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

public class AESTest 
{ 
    public static void main(String [] args)
    {
        String enc = AESEncryptToBase64("000000", "XJ5QJSVMKZGBOQO7HMSIJO5BERW2OYWDVNPM3BH32NLSWUCNJ4FIP3BML7EKUBNO");
        System.out.println(enc);
    }

    /**
     * 
     * @param secret
     * @param cleartext
     * @return encrypted b64 string
     */
    public static String AESEncryptToBase64(String secret, String clearText) {
        byte[] rawKey = new byte[32];
        java.util.Arrays.fill(rawKey, (byte) 0);
        byte[] secretBytes = secret.getBytes();
        for(int i = 0; i < secretBytes.length; i++){
            rawKey[i] = secretBytes[i];
        }

        SecretKeySpec skeySpec = new SecretKeySpec(rawKey, "AES");
        try{ 
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encryptedData = cipher.doFinal(clearText.getBytes());
            if(encryptedData == null) return null;
            // return "l";
            return Base64.encodeBase64String(encryptedData);
        } catch (Exception e){
            e.printStackTrace();
        }
        return null;      

    }
}

编译并运行:


 $ javac -cp "commons-codec-1.7.jar" AESTest.java 
 $ java -cp "commons-codec-1.7.jar" AESTest
 Exception in thread "main" java.lang.NoClassDefFoundError: AESTest
 Caused by: java.lang.ClassNotFoundException: AESTest

这是 apache-commons-codec: http ://apache.mirrors.pair.com//commons/codec/binaries/commons-codec-1.7-bin.zip

4

1 回答 1

3

包含.到您的类路径中:java -cp ".:commons-codec-1.7.jar" AESTest

这将告诉 JVM 将当前文件夹中的类包含到类路径中

于 2012-12-07T16:01:49.180 回答