1

AES加密解密

 2 years ago
source link: https://wakzz.cn/2018/11/16/java/AES%E5%8A%A0%E5%AF%86%E8%A7%A3%E5%AF%86/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

AES加密解密

祈雨的博客
2018-11-16
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class AESUtils {

public static String encrypt(String key, String data) throws Exception {
Cipher cipher = initCipher(key, Cipher.ENCRYPT_MODE);
byte[] encryptedByte = cipher.doFinal(data.getBytes());
return Base64.encodeBase64String(encryptedByte);
}

public static String decrypt(String key, String data) throws Exception {
Cipher cipher = initCipher(key, Cipher.DECRYPT_MODE);
byte[] decryptedByte = cipher.doFinal(Base64.decodeBase64(data));
return new String(decryptedByte);
}

private static Cipher initCipher(String key, int encryptMode) throws Exception {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(encryptMode, new SecretKeySpec(key.getBytes(), "AES"));
return cipher;
}

public static void main(String[] args) throws Exception {
// 16字节秘钥即128比特
String key = "1234567890123456";
String value = "HelloWorld";

// 16进制的加密参数key
System.out.println("key hex: " + Hex.encodeHexString(key.getBytes()));

// 加密
String encrypt = encrypt(key, value);
System.out.println("encrypt: " + encrypt);
// 解密
String decrypt = decrypt(key, encrypt);
System.out.println("decrypt: " + decrypt);
}

}

angular

npm i crypto-js
import CryptoJS from 'crypto-js';

const key = CryptoJS.enc.Utf8.parse('1234567890123456');
const value = CryptoJS.enc.Utf8.parse('HelloWorld');
const encrypted = CryptoJS.AES.encrypt(value, key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
console.log(encrypted.toString());

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK