AES CBC算法/填充在Java/Angular中

huangapple go评论109阅读模式
英文:

AES CBC algorithm/padding in java/angular

问题

我已经在Angular中编写了这段代码以对字符串进行加密:

  1. import { Injectable } from '@angular/core';
  2. import * as CryptoJS from 'crypto-js';
  3. @Injectable({
  4. providedIn: 'root',
  5. })
  6. export class CryptoService {
  7. encrypt(message: string, clef: string): string {
  8. const salt = CryptoJS.SHA256("123456789123");
  9. const key = CryptoJS.PBKDF2(clef, salt, {
  10. keySize: 128 / 32,
  11. iterations: 1000
  12. });
  13. let iv = CryptoJS.enc.Utf8.parse(clef);
  14. let encrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(message.toString()), key,
  15. {
  16. keySize: 128 / 8,
  17. iv: iv,
  18. mode: CryptoJS.mode.CBC,
  19. padding: CryptoJS.pad.Pkcs7
  20. });
  21. return encrypted.toString();
  22. }
  23. generateKey(): string {
  24. let result = '';
  25. const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  26. const charactersLength = characters.length;
  27. let counter = 0;
  28. while (counter < 16) {
  29. result += characters.charAt(Math.floor(Math.random() * charactersLength));
  30. counter += 1;
  31. }
  32. return result;
  33. }
  34. }

我将密钥和加密后的消息传递到后端进行解密。

在Java中,我编写了以下代码:

  1. import java.security.InvalidAlgorithmParameterException;
  2. import java.security.InvalidKeyException;
  3. import java.security.NoSuchAlgorithmException;
  4. import java.security.spec.InvalidKeySpecException;
  5. import java.security.spec.KeySpec;
  6. import java.util.Base64;
  7. import javax.crypto.BadPaddingException;
  8. import javax.crypto.Cipher;
  9. import javax.crypto.IllegalBlockSizeException;
  10. import javax.crypto.NoSuchPaddingException;
  11. import javax.crypto.SecretKey;
  12. import javax.crypto.SecretKeyFactory;
  13. import javax.crypto.spec.IvParameterSpec;
  14. import javax.crypto.spec.PBEKeySpec;
  15. public class AESUtilService {
  16. protected static final String salt = "123456789123";
  17. public SecretKey getKeyFromPassword(String password)
  18. throws NoSuchAlgorithmException, InvalidKeySpecException {
  19. SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
  20. KeySpec spec = new PBEKeySpec(password.toCharArray(), salt.getBytes(), 1000, 128/32);
  21. SecretKey secret = factory.generateSecret(spec);
  22. return secret;
  23. }
  24. public String decrypt(String cipherText, SecretKey key)
  25. throws NoSuchPaddingException, NoSuchAlgorithmException,
  26. InvalidAlgorithmParameterException, InvalidKeyException,
  27. BadPaddingException, IllegalBlockSizeException {
  28. String algorithm = "AES/CBC/PKCS7Padding";
  29. IvParameterSpec iv = new IvParameterSpec("MnTQLHcWumIKTXpQ".getBytes());
  30. Cipher cipher = Cipher.getInstance(algorithm);
  31. cipher.init(Cipher.DECRYPT_MODE, key, iv);
  32. byte[] plainText = cipher.doFinal(Base64.getDecoder().decode(cipherText));
  33. return new String(plainText);
  34. }
  35. }

我的问题如下:
在Java中,如果我使用 String algorithm = "AES/CBC/PKCS7Padding"; 这一行代码会导致程序崩溃。但是如果我使用 String algorithm = "AES/CBC/PKCS5Padding"; 则会通过,但这时在Angular中会崩溃。 padding: CryptoJS.pad.Pkcs5

我找不到这个问题的解决方案,所以我请求您的帮助。

英文:

I have written this code in Angular to encrypt a string:

  1. import { Injectable } from &#39;@angular/core&#39;;
  2. import * as CryptoJS from &#39;crypto-js&#39;;
  3. @Injectable({
  4. providedIn: &#39;root&#39;,
  5. })
  6. export class CryptoService {
  7. encrypt(message: string, clef: string): string {
  8. const salt = CryptoJS.SHA256(&quot;123456789123&quot;);
  9. const key = CryptoJS.PBKDF2(clef, salt, {
  10. keySize: 128 / 32,
  11. iterations: 1000
  12. });
  13. // var key = CryptoJS.enc.Utf8.parse(clef);
  14. let iv = CryptoJS.enc.Utf8.parse(clef);
  15. let encrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(message.toString()), key,
  16. {
  17. keySize: 128 / 8,
  18. iv: iv,
  19. mode: CryptoJS.mode.CBC,
  20. padding: CryptoJS.pad.Pkcs7
  21. });
  22. // var encryptedMessage = CryptoJS.AES.encrypt(message.trim(), key).toString();
  23. return encrypted.toString();
  24. }
  25. generateKey(): string {
  26. let result = &#39;&#39;;
  27. const characters = &#39;ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789&#39;;
  28. const charactersLength = characters.length;
  29. let counter = 0;
  30. while (counter &lt; 16) {
  31. result += characters.charAt(Math.floor(Math.random() * charactersLength));
  32. counter += 1;
  33. }
  34. return result;
  35. }
  36. }

I transfer my key and encriptedMessage to the back for the decryption.

I code dat on java:

  1. import java.security.InvalidAlgorithmParameterException;
  2. import java.security.InvalidKeyException;
  3. import java.security.NoSuchAlgorithmException;
  4. import java.security.spec.InvalidKeySpecException;
  5. import java.security.spec.KeySpec;
  6. import java.util.Base64;
  7. import javax.crypto.BadPaddingException;
  8. import javax.crypto.Cipher;
  9. import javax.crypto.IllegalBlockSizeException;
  10. import javax.crypto.NoSuchPaddingException;
  11. import javax.crypto.SecretKey;
  12. import javax.crypto.SecretKeyFactory;
  13. import javax.crypto.spec.IvParameterSpec;
  14. import javax.crypto.spec.PBEKeySpec;
  15. public class AESUtilService {
  16. protected static final String salt = &quot;123456789123&quot;;
  17. public SecretKey getKeyFromPassword(String password)
  18. throws NoSuchAlgorithmException, InvalidKeySpecException {
  19. SecretKeyFactory factory = SecretKeyFactory.getInstance(&quot;PBKDF2WithHmacSHA256&quot;);
  20. KeySpec spec = new PBEKeySpec(password.toCharArray(), salt.getBytes(), 1000, 128/32);
  21. SecretKey secret = factory.generateSecret(spec);
  22. return secret;
  23. }
  24. public String decrypt(String cipherText, SecretKey key)
  25. throws NoSuchPaddingException, NoSuchAlgorithmException,
  26. InvalidAlgorithmParameterException, InvalidKeyException,
  27. BadPaddingException, IllegalBlockSizeException {
  28. String algorithm = &quot;AES/CBC/PKCS7Padding&quot;;
  29. IvParameterSpec iv = new IvParameterSpec(&quot;MnTQLHcWumIKTXpQ&quot;.getBytes());
  30. Cipher cipher = Cipher.getInstance(algorithm);
  31. cipher.init(Cipher.DECRYPT_MODE, key, iv);
  32. byte[] plainText = cipher.doFinal(Base64.getDecoder().decode(cipherText));
  33. return new String(plainText);
  34. }
  35. }

My issue is the following.
The part of the code Cipher cipher = Cipher.getInstance(algorithm); crashes in java, if I use String algorithm = &quot;AES/CBC/PKCS7Padding&quot;;
However it would pass with String algorithm = &quot;AES/CBC/PKCS5Padding&quot;;, but this time it's angular that would crash. padding: CryptoJS.pad.Pkcs5

I can't find a solution for this problem, and that's why I ask for your help.

答案1

得分: 1

  1. 根据您的代码,似乎存在与PBEKeySpec和密钥长度规范有关的问题。
  2. **JAVA**:您必须使用"AES/CBC/PKCS5Padding"而不是"AES/CBC/PKCS7Padding"
  3. **Angular**:在密钥长度和PBEKeySpec上进行更改
  4. let encrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse("hasan test"), key,
  5. {
  6. keySize: 16,
  7. iv: iv,
  8. mode: CryptoJS.mode.CBC,
  9. padding: CryptoJS.pad.Pkcs7
  10. }).toString();
英文:

As per your code seems like, There is a issue with your PBEKeySpec and key length specification.
JAVA: you must need to use "AES/CBC/PKCS5Padding" instead of "AES/CBC/PKCS7Padding"
Angular: Make changes on key length and PBEKeySpec
let encrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse("hasan test"), key,
{
keySize: 16,
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
}).toString();

答案2

得分: 0

我终于找到一篇帖子说 Java 中的 PKCS5 与 Angular 中的 PKCS7 是相同的 --> 填充(128)。
来源:https://crypto.stackexchange.com/questions/9043/what-is-the-difference-between-pkcs5-padding-and-pkcs7-padding

英文:

I finaly find a post who sayd they pkcs5 in java are the same as pkcs7 in angular
-->padding (128)

source:
https://crypto.stackexchange.com/questions/9043/what-is-the-difference-between-pkcs5-padding-and-pkcs7-padding

huangapple
  • 本文由 发表于 2023年2月10日 16:56:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/75408841.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定