电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁技術文章
文章詳情頁

Java AES加密和解密教程

瀏覽:9日期:2022-08-19 18:21:46

在本教程中,我們將看到如何使用JDK中的Java密碼體系結構(JCA)來實現AES加密和解密。對稱密鑰塊密碼在數據加密中起重要作用。這意味著同一密鑰可用于加密和解密。高級加密標準(AES)是一種廣泛使用的對稱密鑰加密算法。

AES算法是一種迭代的對稱密鑰塊密碼,它支持128、192和256位的加密密鑰(秘密密鑰),以對128位的塊中的數據進行加密和解密。

在AES中生成密鑰的方法有兩種:從隨機數生成或從給定密碼生成。

在第一種方法中,應該從像SecureRandom類這樣的加密安全(偽)隨機數生成器生成秘密密鑰。為了生成密鑰,我們可以使用KeyGenerator類。讓我們定義一種用于生成大小為n(128、192和256)位的AES密鑰的方法:

public static SecretKey generateKey(int n) throws NoSuchAlgorithmException { KeyGenerator keyGenerator = KeyGenerator.getInstance('AES'); keyGenerator.init(n); SecretKey key = keyGenerator.generateKey(); return key;}

在第二種方法中,可以使用基于密碼的密鑰派生功能(例如PBKDF2)從給定的密碼派生AES秘密密鑰。下面方法可通過65,536次迭代和256位密鑰長度從給定密碼生成AES密鑰:

public static SecretKey getKeyFromPassword(String password, String salt) throws NoSuchAlgorithmException, InvalidKeySpecException {SecretKeyFactory factory = SecretKeyFactory.getInstance('PBKDF2WithHmacSHA256'); KeySpec spec = new PBEKeySpec(password.toCharArray(), salt.getBytes(), 65536, 256); SecretKey secret = new SecretKeySpec(factory.generateSecret(spec).getEncoded(), 'AES'); return secret;}

加密字符串

要實現輸入字符串加密,我們首先需要根據上一節生成密鑰和初始化向量IV:

IV是偽隨機值,其大小與加密的塊相同。我們可以使用SecureRandom類生成隨機IV。

讓我們定義一種生成IV的方法:

public static IvParameterSpec generateIv() { byte[] iv = new byte[16]; new SecureRandom().nextBytes(iv); return new IvParameterSpec(iv);}

下一步,我們使用getInstance()方法從Cipher類創建一個實例。

此外,我們使用帶有秘密密鑰,IV和加密模式的init()方法配置密碼實例。最后,我們通過調用doFinal()方法對輸入字符串進行加密。此方法獲取輸入字節并以字節為單位返回密文:

public static String encrypt(String algorithm, String input, SecretKey key, IvParameterSpec iv) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {Cipher cipher = Cipher.getInstance(algorithm); cipher.init(Cipher.ENCRYPT_MODE, key, iv); byte[] cipherText = cipher.doFinal(input.getBytes()); return Base64.getEncoder().encodeToString(cipherText);}

為了解密輸入字符串,我們可以使用DECRYPT_MODE初始化密碼來解密內容:

public static String decrypt(String algorithm, String cipherText, SecretKey key, IvParameterSpec iv) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {Cipher cipher = Cipher.getInstance(algorithm); cipher.init(Cipher.DECRYPT_MODE, key, iv); byte[] plainText = cipher.doFinal(Base64.getDecoder().decode(cipherText)); return new String(plainText);}

編寫一個用于加密和解密字符串輸入的測試方法:

@Testvoid givenString_whenEncrypt_thenSuccess() throws NoSuchAlgorithmException, IllegalBlockSizeException, InvalidKeyException, BadPaddingException, InvalidAlgorithmParameterException, NoSuchPaddingException { String input = 'baeldung'; SecretKey key = AESUtil.generateKey(128); IvParameterSpec ivParameterSpec = AESUtil.generateIv(); String algorithm = 'AES/CBC/PKCS5Padding'; String cipherText = AESUtil.encrypt(algorithm, input, key, ivParameterSpec); String plainText = AESUtil.decrypt(algorithm, cipherText, key, ivParameterSpec); Assertions.assertEquals(input, plainText);}

加密文件

現在,讓我們使用AES算法加密文件。步驟是相同的​​,但是我們需要一些IO類來處理文件。讓我們加密一個文本文件:

public static void encryptFile(String algorithm, SecretKey key, IvParameterSpec iv, File inputFile, File outputFile) throws IOException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {Cipher cipher = Cipher.getInstance(algorithm); cipher.init(Cipher.ENCRYPT_MODE, key, iv); FileInputStream inputStream = new FileInputStream(inputFile); FileOutputStream outputStream = new FileOutputStream(outputFile); byte[] buffer = new byte[64]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) {byte[] output = cipher.update(buffer, 0, bytesRead);if (output != null) { outputStream.write(output);} } byte[] outputBytes = cipher.doFinal(); if (outputBytes != null) {outputStream.write(outputBytes); } inputStream.close(); outputStream.close();}

請注意,不建議嘗試將整個文件(尤其是大文件)讀入內存。相反,我們一次加密一個緩沖區。

為了解密文件,我們使用類似的步驟,并使用DECRYPT_MODE初始化密碼,如前所述。

再次,讓我們定義一個用于加密和解密文本文件的測試方法。在這種方法中,我們從測試資源目錄中讀取baeldung.txt文件,將其加密為一個名為baeldung.encrypted的文件,然后將該文件解密為一個新文件:

@Testvoid givenFile_whenEncrypt_thenSuccess() throws NoSuchAlgorithmException, IOException, IllegalBlockSizeException, InvalidKeyException, BadPaddingException, InvalidAlgorithmParameterException, NoSuchPaddingException {SecretKey key = AESUtil.generateKey(128); String algorithm = 'AES/CBC/PKCS5Padding'; IvParameterSpec ivParameterSpec = AESUtil.generateIv(); Resource resource = new ClassPathResource('inputFile/baeldung.txt'); File inputFile = resource.getFile(); File encryptedFile = new File('classpath:baeldung.encrypted'); File decryptedFile = new File('document.decrypted'); AESUtil.encryptFile(algorithm, key, ivParameterSpec, inputFile, encryptedFile); AESUtil.decryptFile( algorithm, key, ivParameterSpec, encryptedFile, decryptedFile); assertThat(inputFile).hasSameTextualContentAs(decryptedFile);}

基于密碼加密解密

我們可以使用從給定密碼派生的密鑰進行AES加密和解密。

為了生成密鑰,我們使用getKeyFromPassword()方法。加密和解密步驟與字符串輸入部分中顯示的步驟相同。然后,我們可以使用實例化的密碼和提供的密鑰來執行加密。

讓我們寫一個測試方法:

@Testvoid givenPassword_whenEncrypt_thenSuccess() throws InvalidKeySpecException, NoSuchAlgorithmException, IllegalBlockSizeException, InvalidKeyException, BadPaddingException, InvalidAlgorithmParameterException, NoSuchPaddingException {String plainText = 'www.baeldung.com'; String password = 'baeldung'; String salt = '12345678'; IvParameterSpec ivParameterSpec = AESUtil.generateIv(); SecretKey key = AESUtil.getKeyFromPassword(password,salt); String cipherText = AESUtil.encryptPasswordBased(plainText, key, ivParameterSpec); String decryptedCipherText = AESUtil.decryptPasswordBased( cipherText, key, ivParameterSpec); Assertions.assertEquals(plainText, decryptedCipherText);}

加密對象

為了加密Java對象,我們需要使用SealedObject類。該對象應可序列化。讓我們從定義學生類開始:

public class Student implements Serializable { private String name; private int age; // standard setters and getters}

接下來,讓我們加密Student對象:

public static SealedObject encryptObject(String algorithm, Serializable object, SecretKey key, IvParameterSpec iv) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, IOException, IllegalBlockSizeException {Cipher cipher = Cipher.getInstance(algorithm); cipher.init(Cipher.ENCRYPT_MODE, key, iv); SealedObject sealedObject = new SealedObject(object, cipher); return sealedObject;}

稍后可以使用正確的密碼解密加密的對象:

public static Serializable decryptObject(String algorithm, SealedObject sealedObject, SecretKey key, IvParameterSpec iv) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, ClassNotFoundException, BadPaddingException, IllegalBlockSizeException, IOException {Cipher cipher = Cipher.getInstance(algorithm); cipher.init(Cipher.DECRYPT_MODE, key, iv); Serializable unsealObject = (Serializable) sealedObject.getObject(cipher); return unsealObject;}

讓我們寫一個測試用例:

@Testvoid givenObject_whenEncrypt_thenSuccess() throws NoSuchAlgorithmException, IllegalBlockSizeException, InvalidKeyException, InvalidAlgorithmParameterException, NoSuchPaddingException, IOException, BadPaddingException, ClassNotFoundException {Student student = new Student('Baeldung', 20); SecretKey key = AESUtil.generateKey(128); IvParameterSpec ivParameterSpec = AESUtil.generateIv(); String algorithm = 'AES/CBC/PKCS5Padding'; SealedObject sealedObject = AESUtil.encryptObject( algorithm, student, key, ivParameterSpec); Student object = (Student) AESUtil.decryptObject( algorithm, sealedObject, key, ivParameterSpec); assertThat(student).isEqualToComparingFieldByField(object);}

可以在GitHub上獲得本文的完整源代碼 。

以上就是Java AES加密和解密教程的詳細內容,更多關于Java AES加密和解密的資料請關注好吧啦網其它相關文章!

標簽: Java
相關文章:
主站蜘蛛池模板: 玻璃瓶厂家_酱菜瓶厂家_饮料瓶厂家_酒瓶厂家_玻璃杯厂家_徐州东明玻璃制品有限公司 | 智慧消防-消防物联网系统云平台 智能化的检漏仪_气密性测试仪_流量测试仪_流阻阻力测试仪_呼吸管快速检漏仪_连接器防水测试仪_车载镜头测试仪_奥图自动化科技 | 东莞爱加真空科技有限公司-进口真空镀膜机|真空镀膜设备|Polycold维修厂家 | led全彩屏-室内|学校|展厅|p3|户外|会议室|圆柱|p2.5LED显示屏-LED显示屏价格-LED互动地砖屏_蕙宇屏科技 | 水篦子|雨篦子|镀锌格栅雨水篦子|不锈钢排水篦子|地下车库水箅子—安平县云航丝网制品厂 | 一技任务网_有一技之长,就来技术任务网 | WF2户外三防照明配电箱-BXD8050防爆防腐配电箱-浙江沃川防爆电气有限公司 | Eiafans.com_环评爱好者 环评网|环评论坛|环评报告公示网|竣工环保验收公示网|环保验收报告公示网|环保自主验收公示|环评公示网|环保公示网|注册环评工程师|环境影响评价|环评师|规划环评|环评报告|环评考试网|环评论坛 - Powered by Discuz! | 爆炸冲击传感器-无线遥测传感器-航天星百科| 首页_中夏易经起名网| 废水处理-废气处理-工业废水处理-工业废气处理工程-深圳丰绿环保废气处理公司 | 环氧树脂地坪漆_济宁市新天地漆业有限公司 | 变色龙PPT-国内原创PPT模板交易平台 - PPT贰零 - 西安聚讯网络科技有限公司 | 云南成人高考_云南成考网| 天津货架厂_穿梭车货架_重型仓储货架_阁楼货架定制-天津钢力仓储货架生产厂家_天津钢力智能仓储装备 | 电动卫生级调节阀,电动防爆球阀,电动软密封蝶阀,气动高压球阀,气动对夹蝶阀,气动V型调节球阀-上海川沪阀门有限公司 | SDG吸附剂,SDG酸气吸附剂,干式酸性气体吸收剂生产厂家,超过20年生产使用经验。 - 富莱尔环保设备公司(原名天津市武清县环保设备厂) | 合肥汽车充电桩_安徽充电桩_电动交流充电桩厂家_安徽科帝新能源科技有限公司 | 贵州科比特-防雷公司厂家提供贵州防雷工程,防雷检测,防雷接地,防雷设备价格,防雷产品报价服务-贵州防雷检测公司 | 干粉砂浆设备_干混砂浆生产线_腻子粉加工设备_石膏抹灰砂浆生产成套设备厂家_干粉混合设备_砂子烘干机--郑州铭将机械设备有限公司 | 细砂提取机,隔膜板框泥浆污泥压滤机,螺旋洗砂机设备,轮式洗砂机械,机制砂,圆锥颚式反击式破碎机,振动筛,滚筒筛,喂料机- 上海重睿环保设备有限公司 | 杭州营业执照代办-公司变更价格-许可证办理流程_杭州福道财务管理咨询有限公司 | 钢制暖气片散热器_天津钢制暖气片_卡麦罗散热器厂家 | 广西资质代办_建筑资质代办_南宁资质代办理_新办、增项、升级-正明集团 | 金属清洗剂,防锈油,切削液,磨削液-青岛朗力防锈材料有限公司 | 维泰克Veertek-锂电池微短路检测_锂电池腐蚀检测_锂电池漏液检测 | 北京京云律师事务所 | 薪动-人力资源公司-灵活用工薪资代发-费用结算-残保金优化-北京秒付科技有限公司 | 深圳侦探联系方式_深圳小三调查取证公司_深圳小三分离机构 | 横河变送器-横河压力变送器-EJA变送器-EJA压力变送器-「泉蕴仪表」 | b2b网站大全,b2b网站排名,找b2b网站就上地球网 | 河南档案架,档案密集架,手动密集架,河南密集架批发/报价 | 一体化净水器_一体化净水设备_一体化水处理设备-江苏旭浩鑫环保科技有限公司 | 青岛成人高考_山东成考报名网 | 车间除尘设备,VOCs废气处理,工业涂装流水线,伸缩式喷漆房,自动喷砂房,沸石转轮浓缩吸附,机器人喷粉线-山东创杰智慧 | 模切之家-专注服务模切行业的B2B平台!| 回转支承-转盘轴承-回转驱动生产厂家-洛阳隆达轴承有限公司 | 新车测评网_网罗汽车评测资讯_汽车评测门户报道 | 杭州用友|用友软件|用友财务软件|用友ERP系统--杭州协友软件官网 | 根系分析仪,大米外观品质检测仪,考种仪,藻类鉴定计数仪,叶面积仪,菌落计数仪,抑菌圈测量仪,抗生素效价测定仪,植物表型仪,冠层分析仪-杭州万深检测仪器网 | 「阿尔法设计官网」工业设计_产品设计_产品外观设计 深圳工业设计公司 |