接口傳輸數據加密、解密、加簽、驗簽(AES,RSA,Sign)


接口傳輸數據加密、解密、加簽、驗簽(AES,RSA,Sign)

理解公鑰與私鑰:https://songlee24.github.io/2015/05/03/public-key-and-private-key/

Demo

public static void testCert() {
        RSA rsa = new RSA();
        String publicKey = rsa.getPublicKeyBase64();
        String privateKey = rsa.getPrivateKeyBase64();

        /* 加密 */
        // 傳輸的數據
        String data = "data";
        // 加密的 key
        String key = RandomUtil.randomNumbers(16);
        // 根據生成的key構造 AES 加密算法(個人理解,key就像一把鑰匙,解密的時候要用這把鑰匙)
        AES aes = new AES(Mode.ECB, Padding.PKCS5Padding, key.getBytes());
        // 根據構造出來的 aes 加密算法對數據進行加密
        String encryptDataBase64 = aes.encryptBase64(data);


        // RSA 使用 公鑰 進行簽名加密
        RSA platRsa = new RSA(null, publicKey);
        // 使用 公鑰 對加密數據的 key 進行加密(對數據加密的鑰匙進行加密)
        String encryptKeyBase64 = platRsa.encryptBase64(key, KeyType.PublicKey);


        // 構建簽名實例
        Sign appSign = new Sign(SignAlgorithm.SHA1withRSA, privateKey, publicKey);
        // 用私鑰對信息生成數字簽名 並 進行base64處理
        String signBase64 = Base64.encode(appSign.sign(data.getBytes()));
        System.out.println("sign:" + signBase64);
      
     發送:
     encryptDataBase64,加密后的數據
     encryptKeyBase64,加密后的key
     signBase64 ,簽名給對方



/* 解密 */ // 使用公鑰、私鑰 構造 RSA實例 RSA appRsa = new RSA(privateKey, publicKey); // 解密、加密數據的 key key = appRsa.decryptStr(encryptKeyBase64, KeyType.PrivateKey); // 構建解密數據的實例 aes = new AES(Mode.ECB, Padding.PKCS5Padding, key.getBytes()); // 解密傳輸的數據 String plaintextData = aes.decryptStr(encryptDataBase64); // 構建 Sign 實例,驗簽使用 Sign platSign = new Sign(SignAlgorithm.SHA1withRSA, null, publicKey); // 用公鑰檢驗數字簽名的合法性 boolean verify = platSign.verify(plaintextData.getBytes(), Base64.decode(signBase64)); System.out.println("驗證簽名:" + verify); if (verify) { System.out.println("驗證簽名成功"); } else { System.out.println("驗證簽名失敗"); } }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM