栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java数据的加解密(RSA与AES)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java数据的加解密(RSA与AES)

RSA为不对称的加密算法,用公钥加密、私钥解密,一般用于加密数据量不是很大的数据,比如加密密钥,比如数据签名、验证。

AES为对称加密,非对齐的加密数据长度亦要至少能被16整除,密码也至少16位,如果用128位CBC方式,还要提个一个初始向量iv,亦要是16位。

利用空档时间手写了一个cipher库
pom引用


  io.github.tiger822
  cipher
  1.0

1、RSA加解密
	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));
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/737658.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号