AES加密代码

 

这里分享AES的加密代码,包含两种填充方式PKCS7Padding和PKCS5Padding。代码中加密后的数据再加密成Base64形式,这一部分也可以换成16进制的形式。

Java本身是不支持PKCS7Padding加密、解密的,因此需要添加外部依赖。

<!-- https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk15on -->
<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcprov-jdk15on</artifactId>
    <version>1.60</version>
</dependency>
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.Security;

public class AESTest {

    //添加AES/ECB/PKCS7Padding的加密与解密方式
    static {
        if (Security.getProvider("BC") == null) {
            Security.addProvider(new BouncyCastleProvider());
        } else {
            Security.removeProvider("BC");
            Security.addProvider(new BouncyCastleProvider());
        }
    }

    //AES/ECB/PKCS5Padding加密
    private static String encode(String data, String privateKey) {
        try {
            Key key = generateKey(privateKey);
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] bytes = cipher.doFinal(data.getBytes());
            return new String(Base64.encode(bytes));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //AES/ECB/PKCS5Padding解密
    private static String decode(String data, String privateKey) {
        try {
            Key key = generateKey(privateKey);
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] bytes = cipher.doFinal(Base64.decode(data.getBytes()));
            return new String(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //AES/ECB/PKCS7Padding加密
    private static String encodeWithPKCS7Padding(String data, String privateKey) {
        try {
            Key key = generateKey(privateKey);
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] bytes = cipher.doFinal(data.getBytes());
            return new String(Base64.encode(bytes));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //AES/ECB/PKCS7Padding解密
    private static String decodeWithPKCS7Padding(String data, String privateKey) {
        try {
            Key key = generateKey(privateKey);
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC");
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] bytes = cipher.doFinal(Base64.decode(data.getBytes()));
            return new String(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static Key generateKey(String privateKey) {
        return new SecretKeySpec(privateKey.getBytes(), "AES");
    }

    public static void main(String[] args) {
        //密钥需要16位
        String privateKey = "12349876abcdzyxw";
        String data = "This is a demo.";

        String encode = encode(data, privateKey);
        String decode = decode(encode, privateKey);
        System.out.println("加密前数据:" + data + "\n加密后数据:" + encode + "\n解密数据:" + decode);

        System.out.println("----------------------------------------------------------------------");

        String encodeWithPKCS7Padding = encodeWithPKCS7Padding(data, privateKey);
        String decodeWithPKCS7Padding = decodeWithPKCS7Padding(encodeWithPKCS7Padding, privateKey);
        System.out.println("加密前数据:" + data + "\n加密后数据:" + encodeWithPKCS7Padding + "\n解密数据:" + decodeWithPKCS7Padding);
    }
}

参考链接:https://blog.csdn.net/lijun169/article/details/82736103

aes加密代码,非常完整,包括加密解密。 AESCrypt File Format Description Items in quotes are a literal string. Words outside of quotes are a textual description of the contents. Fixed-valued octets are written in hexidecimal form (e.g., 0x01). The AESCrypt version 2 file format is as follows. 3 Octets - 'AES' 1 Octet - 0x02 (Version) 1 Octet - Reserved .... Start of repeating extension block section 2 Octet - Length in octets (in network byte order) of an extension identifier and contents. If 0x0000, then no further extensions exist and the next octet is the start of the Initialization Vector (IV). Following an extension, this length indicator would appear again to indicate presence or absense of another extension and the size of any such extension. nn Octets - Extension identifier. This is either a URI or an identifier defined by the AES developer community and documented on the standard extensions page, either of which is terminated by a single 0x00 octet. All extension identifiers are case sensitive. Examples of URIs: http://www.aescrypt.com/extensions/creator/ urn:oid:1.3.6.1.4.1.17090.55.14 urn:uuid:85519EA3-1DA6-45b9-9041-8CD368D8C086 Note: A URI was used to allow anybody to define extension types, though we should strive to define a standard set of extensions. Examples of standard extension identifiers: CREATED-DATE CREATED-BY A special extension is defined that has no name, but is merely a "container" for extensions to be added after the AES file is initially created. Such an extension avoids the need to read and re-write the entire file in order to add a small extension. Software tools that create AES files should insert a 128-octet "container" extension, placing a 0x00 in the first octet of the extension identifier field. Developers may then insert extensions into this "container" area and reduce the size of this "container" as necessary. If larger extensions are added or the "container" area is filled entirely, then reading and re-writing the entire file would be necessary to add additional extensions. nn Octets - The contents of the extension .... End of repeating extension block section 16 Octets - Initialization Vector (IV) used for encrypting the IV and symmetric key that is actually used to encrypt the bulk of the plaintext file. 48 Octets - Encrypted IV and 256-bit AES key used to encrypt the bulk of the file 16 octets - Initialization Vector 32 octets - encryption key 32 Octets - HMAC nn Octets - Encrypted message (2^64 octets max) 1 Octet - File size modulo 16 in least significant bit positions 32 Octets - HMAC Thus, the footprint of the file is at least 136 octets. The AESCrypt version 1 file format is as follows. 3 Octets - 'AES' 1 Octet - 0x01 (Version) 1 Octet - Reserved 16 Octets - Initialization Vector (IV) used for encrypting the IV and symmetric key that is actually used to encrypt the bulk of the plaintext file. 48 Octets - Encrypted IV and 256-bit AES key used to encrypt the bulk of the file 16 octets - Initialization Vector 32 octets - encryption key 32 Octets - HMAC nn Octets - Encrypted message (2^64 octets max) 1 Octet - File size modulo 16 in least significant bit positions 32 Octets - HMAC Thus, the footprint of the file is at least 134 octets. The AESCrypt version 0 file format is as follows. 3 Octets - 'AES' 1 Octet - 0x00 (Version) 1 Octet - File size modulo 16 in least significant bit positions 16 Octets - Initialization Vector (IV) nn Octets - Encrypted message (2^64 octets max) 32 Octets - HMAC Thus, the footprint of the file is at least 53 octets.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值