RSA为不对称的加密算法,用公钥加密、私钥解密,一般用于加密数据量不是很大的数据,比如加密密钥,比如数据签名、验证。
AES为对称加密,非对齐的加密数据长度亦要至少能被16整除,密码也至少16位,如果用128位CBC方式,还要提个一个初始向量iv,亦要是16位。
利用空档时间手写了一个cipher库
pom引用
1、RSA加解密io.github.tiger822 cipher 1.0
KeyPair keyPair= RSAUtil.buildKeyPair();
String publicKeyStr= base64Utils.encode( keyPair.getPublic().getEncoded());
String privateKeyStr= base64Utils.encode(keyPair.getPrivate().getEncoded());
System.out.println("public key:"+publicKeyStr);
System.out.println("private key:"+privateKeyStr);
CipherUtil cipher1=new RSAUtil(publicKeyStr);
cipher1.initCipher();
String rawText="我是要加密的字符串,This is a string that needs to be encrypted";
byte[] encrypted= cipher1.encrypt(rawText.getBytes());
System.out.println("加密后的内容:"+base64Utils.encode(encrypted));
byte[] e2=cipher1.encrypt("String 2".getBytes());
CipherUtil cipher2=new RSAUtil((RSAPrivateCrtKey) keyPair.getPrivate());
cipher2.initCipher();
String plaintext=new String(cipher2.decrypt(encrypted));
System.out.println("解密后的明文:"+plaintext);
System.out.println(new String(cipher2.decrypt(e2)));
2、签名、确认
String test="this the string that need to protect";
KeyPair keyPair= RSAUtil.buildKeyPair();
CipherUtil cipherUtil=new RSAUtil((RSAPrivateKey) keyPair.getPrivate());
byte[] signCode=cipherUtil.sign(test.getBytes());
System.out.println("签名:"+base64Utils.encode(signCode));
CipherUtil cipherUtil2=new RSAUtil(keyPair.getPublic().getEncoded());
if (cipherUtil2.verify(signCode,test.getBytes())){
System.out.println("验证通过");
}
if (!cipherUtil2.verify(signCode,(test+".").getBytes())){
System.out.println("验证失败");
}
3、AES加解密
String rawText="这是加密字符串, I need to encrypt.";
String password="abcd@1234";
String iv="123456";
CipherUtil aes=new AESUtil(password,iv);
aes.initCipher();
byte[] secret=null;
for (int i=0;i<3;i++){
secret= aes.encrypt(rawText.getBytes());
System.out.println("AES加密后:"+base64Utils.encode(secret));
}
CipherUtil aesDesc=new AESUtil(password,iv);
aesDesc.initCipher();
byte[] plaintContent=aesDesc.decrypt(secret);
System.out.println("解密后:"+new String(plaintContent));



