簡體   English   中英

使用 JDK 7 使用 AES 128 時的問題

[英]Issue when using AES 128 using JDK 7

我有一個從 Mainframe_JCL 觸發的獨立 Java 程序。 Java 程序有一個代碼來加密和解密一個字符串。

當我在本地運行程序時。 加密后,當我解密時,該值是正確的(我得到了我為加密提供的字符串)。

但是當它通過 JCL 在大型機上運行時執行這個.. 我得到了奇怪的解密值.. 有點垃圾。

不知道是什么問題。 任何幫助,將不勝感激。

我們使用以下 JDK:IBM SDK for z/OS,Java 技術版,版本 7

以下是用於加密和解密的方法:

    public static String encrypt(String text) throws UnsupportedEncodingException {
        byte iv[] = new byte[16];
        byte[] encrypted = null;
        BASE64Encoder enc = new BASE64Encoder();
        try {            
            SecureRandom random = new SecureRandom();
            random.nextBytes(iv);
            IvParameterSpec ivspec = new IvParameterSpec(iv);
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, getKeySpec(), ivspec);
            encrypted = cipher.doFinal(text.getBytes());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return URLEncoder.encode(enc.encode(iv)+enc.encode(encrypted), "UTF-8");
    }

    public static String decrypt(String text) {
        byte iv[] = new byte[16];
        String decrypted  = "";
        byte[] splitText = null;
        byte[] textToDecrypt = null;
        BASE64Decoder dec = new BASE64Decoder();
        try { 
            text = URLDecoder.decode(text, "UTF-8");
            text = text.replaceAll(" ", "+");
            splitText = dec.decodeBuffer(text);
            splitText.toString();
            for(int i=0;i<16;i++){
                iv[i]=splitText[i];
            }
            textToDecrypt = new byte[splitText.length - 16];
            for(int i=16;i<splitText.length;i++){
                textToDecrypt[i-16]=splitText[i];
            }
            IvParameterSpec ivspec = new IvParameterSpec(iv);
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, getKeySpec(), ivspec);
           decrypted = new String(cipher.doFinal(textToDecrypt));
        } catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
        }
        return decrypted;
    }

static SecretKeySpec spec = null;
public static SecretKeySpec getKeySpec() throws IOException,
                                            NoSuchAlgorithmException {
    if (spec == null) {
        String keyFile = "aes_key.key";
        spec = null;
        InputStream fis = null;
        fis = Config.class.getClassLoader().getResourceAsStream(keyFile);
        byte[] rawkey = new byte[16];
        fis.read(rawkey);
        fis.close();
        spec = new SecretKeySpec(rawkey, "AES");
}
return spec;
}

你沒有提供足夠的信息來運行你的代碼(所以我不會修復),但我看到兩件事可能會破壞結果:

  1. 在使用 Base64 編碼之前,您應該在 16 字節 IV 前加上前綴; 目前您可能正在混合 IV 和密文。
  2. 您應該為toBytesnew String定義字符編碼; 目前您可能有兩個不同的平台字符集來滿足。

最后,URL 編碼 base 64 可能不是很有效,你最好只用URL 安全對應物替換+/字符。


所以我有一個謎題:

package nl.owlstead.stackoverflow;

import static java.nio.charset.StandardCharsets.UTF_8;

import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public final class VeryStaticStringEncryption {

    private static final String KEY_FILE = "aes_key.key";
    private static final SecretKey AES_KEY = retrieveSecretKey(KEY_FILE);

    private VeryStaticStringEncryption() {
        // avoid instantiation
    }

    public static String encrypt(final String text) {
        try {
            final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            final int n = cipher.getBlockSize();

            final SecureRandom random = new SecureRandom();
            final byte[] iv = new byte[n];
            random.nextBytes(iv);
            final IvParameterSpec ivspec = new IvParameterSpec(iv);

            cipher.init(Cipher.ENCRYPT_MODE, AES_KEY, ivspec);

            final byte[] plaintext = text.getBytes(UTF_8);
            byte[] ciphertext = Arrays.copyOf(iv,
                    n + cipher.getOutputSize(plaintext.length));
            final int ciphertextSize = cipher.doFinal(
                    plaintext, 0, plaintext.length,
                    ciphertext, n);

            // output size may be bigger, but not likely
            if (n + ciphertextSize  < ciphertext.length) {
                ciphertext = Arrays.copyOf(ciphertext, n + ciphertextSize);
            }

            return Base64.getUrlEncoder().encodeToString(ciphertext);
        } catch (final GeneralSecurityException e) {
            throw new IllegalStateException("Could not encrypt string", e);
        }
    }

    public static String decrypt(final String text) {
        try {
            // throws IllegalArgumentException if decoding fails
            final byte[] ciphertext = Base64.getUrlDecoder().decode(text);

            final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            final int n = cipher.getBlockSize();

            // CBC specific
            if (ciphertext.length < n + n || ciphertext.length % n != 0) {
                throw new IllegalArgumentException("Ciphertext has incorrect size");
            }

            final IvParameterSpec ivspec = new IvParameterSpec(ciphertext, 0, n);
            cipher.init(Cipher.DECRYPT_MODE, AES_KEY, ivspec);
            final byte[] plaintext = cipher.doFinal(ciphertext, n, ciphertext.length - n);
            return new String(plaintext, UTF_8);
        } catch (final GeneralSecurityException e) {
            throw new IllegalStateException("Could not encrypt string", e);
        }
    }

    public static SecretKey retrieveSecretKey(final String keyResource) {
        try (final InputStream fis = VeryStaticStringEncryption.class.getResourceAsStream(keyResource)) {
            final byte[] rawkey = new byte[16];
            for (int i = 0; i < 16; i++) {
                final int b = fis.read();
                if (b == -1) {
                    throw new IOException("Key is not 16 bytes");
                }
                rawkey[i] = (byte) b;
            }

            if (fis.read() != -1) {
                throw new IOException("Key is not 16 bytes");
            }

            return new SecretKeySpec(rawkey, "AES");
        } catch (final IOException e) {
            // e may contain confidential information
            throw new IllegalStateException("AES key resource not available");
        }
    }

    public static void main(String[] args) {
        String ct = encrypt("owlstead");
        System.out.println(ct);
        String pt = decrypt(ct);
        System.out.println(pt);
    }
}

請注意,我使用了包本地資源,因為我不想弄亂我的 SO 項目。

重要說明:如果可能存在中間人攻擊,CBC 加密對於傳輸模式加密是不安全的。 如果需要,重構為 GCM 模式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM