JAVA加解密方法
import org.apache.commons.lang3.Validate;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
public class AesTools {
public static final String KEY = "eyJhbGciOiJIUzUxMiJ9eyJhbGciOiJIUzUx";
private static SecretKeySpec getKey() {
byte[] arrBTemp = KEY.getBytes();
byte[] arrB = new byte[16];
for (int i = 0; i < arrBTemp.length && i < arrB.length; i++) {
arrB[i] = arrBTemp[i];
}
SecretKeySpec keySpec = new SecretKeySpec(arrB, "AES");
return keySpec;
}
public static String encrypt(String content) {
try {
Validate.notBlank(content);
SecretKeySpec keySpec = getKey();
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec("0102030405060708".getBytes());
cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);
byte[] encrypted = cipher.doFinal(content.getBytes());
return new BASE64Encoder().encode(encrypted);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("encrypt error");
}
}
public static String decrypt(String content) {
try {
Validate.notBlank(content);
byte[] base64Str = new BASE64Decoder().decodeBuffer(content);
SecretKeySpec keySpec = getKey();
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec("0102030405060708".getBytes());
cipher.init(Cipher.DECRYPT_MODE, keySpec, iv);
byte[] decryptByte =cipher.doFinal(base64Str);
return new String(decryptByte);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("decrypt error");
}
}
public static void main(String[] args) {
System.out.println(encrypt("sdsdsfsdf"));
System.out.println(decrypt("J34NoQqnqSIK10+RsBnXww=="));
}
}
ruby加解密方法
require 'openssl'
require 'base64'
def encrypt_data(encryptStr)
key = "eyJhbGciOiJIUzUxMiJ9eyJhbGciOiJIUzUx"
iv = "0102030405060708"
key = key
cipher = OpenSSL::Cipher::Cipher.new('aes-128-cbc')
cipher.encrypt
cipher.key = key
cipher.iv = iv
text = cipher.update(encryptStr) + cipher.final
encrypted_text = Base64.strict_encode64(text)
return encrypted_text
end
def decrypt_data(decryptStr)
key = "eyJhbGciOiJIUzUxMiJ9eyJhbGciOiJIUzUx"
iv = "0102030405060708"
key = key
cipher = OpenSSL::Cipher::Cipher.new('aes-128-cbc')
cipher.decrypt
cipher.key = key
cipher.iv = iv
text = cipher.update( Base64::strict_decode64(decryptStr)) + cipher.final
return text
end
puts encrypt_data("sdsdsfsdf")
puts decrypt_data("J34NoQqnqSIK10+RsBnXww==")