基於混沌加密的OFDM系統實現,包括混沌序列生成、加密算法設計以及完整的OFDM系統集成

1. 混沌系統與序列生成

1.1 多種混沌系統實現

classdef ChaosEncryption
    % 混沌加密系統
    
    methods (Static)
        function sequence = logistic_map(x0, r, N)
            % Logistic混沌映射
            % x0: 初始值, r: 控制參數, N: 序列長度
            
            sequence = zeros(1, N);
            sequence(1) = x0;
            
            for i = 2:N
                sequence(i) = r * sequence(i-1) * (1 - sequence(i-1));
            end
        end
        
        function sequence = tent_map(x0, mu, N)
            % Tent混沌映射
            sequence = zeros(1, N);
            sequence(1) = x0;
            
            for i = 2:N
                if sequence(i-1) < 0.5
                    sequence(i) = mu * sequence(i-1);
                else
                    sequence(i) = mu * (1 - sequence(i-1));
                end
            end
        end
        
        function sequence = chebyshev_map(x0, k, N)
            % Chebyshev混沌映射
            sequence = zeros(1, N);
            sequence(1) = x0;
            
            for i = 2:N
                sequence(i) = cos(k * acos(sequence(i-1)));
            end
        end
        
        function [x, y] = henon_map(x0, y0, a, b, N)
            % Henon混沌映射
            x = zeros(1, N);
            y = zeros(1, N);
            x(1) = x0;
            y(1) = y0;
            
            for i = 2:N
                x(i) = 1 - a * x(i-1)^2 + y(i-1);
                y(i) = b * x(i-1);
            end
        end
        
        function sequence = generate_chaos_bits(chaos_sequence, threshold)
            % 將混沌序列轉換為二進制序列
            if nargin < 2
                threshold = 0.5;
            end
            
            sequence = chaos_sequence > threshold;
        end
        
        function encrypted_bits = chaos_encrypt_bits(data_bits, chaos_bits)
            % 使用混沌序列對二進制數據進行加密 (異或操作)
            encrypted_bits = xor(data_bits, chaos_bits(1:length(data_bits)));
        end
        
        function decrypted_bits = chaos_decrypt_bits(encrypted_bits, chaos_bits)
            % 使用混沌序列對加密數據進行解密 (異或操作)
            decrypted_bits = xor(encrypted_bits, chaos_bits(1:length(encrypted_bits)));
        end
    end
end

1.2 增強型混沌序列生成器

classdef EnhancedChaosSystem
    % 增強型混沌序列生成系統
    
    properties
        chaos_type        % 混沌類型
        parameters       % 參數集合
        initial_conditions % 初始條件
    end
    
    methods
        function obj = EnhancedChaosSystem(type, varargin)
            % 構造函數
            obj.chaos_type = type;
            
            p = inputParser;
            switch lower(type)
                case 'logistic'
                    addParameter(p, 'r', 3.99, @(x) x>0);
                    addParameter(p, 'x0', 0.5, @(x) x>0 && x<1);
                case 'tent'
                    addParameter(p, 'mu', 1.999, @(x) x>0);
                    addParameter(p, 'x0', 0.5, @(x) x>0 && x<1);
                case 'chebyshev'
                    addParameter(p, 'k', 4, @(x) x>0);
                    addParameter(p, 'x0', 0.5, @(x) x>0 && x<1);
                case 'henon'
                    addParameter(p, 'a', 1.4, @(x) x>0);
                    addParameter(p, 'b', 0.3, @(x) x>0);
                    addParameter(p, 'x0', 0.1, @(x) x>0);
                    addParameter(p, 'y0', 0.1, @(x) x>0);
            end
            parse(p, varargin{:});
            
            obj.parameters = p.Results;
            obj.initial_conditions = p.Results;
        end
        
        function sequence = generate_sequence(obj, N, varargin)
            % 生成混沌序列
            p = inputParser;
            addParameter(p, 'remove_transient', 1000, @(x) x>=0);
            parse(p, varargin{:});
            
            remove_N = p.Results.remove_transient;
            total_N = N + remove_N;
            
            switch lower(obj.chaos_type)
                case 'logistic'
                    seq = ChaosEncryption.logistic_map(...
                        obj.initial_conditions.x0, ...
                        obj.parameters.r, total_N);
                    
                case 'tent'
                    seq = ChaosEncryption.tent_map(...
                        obj.initial_conditions.x0, ...
                        obj.parameters.mu, total_N);
                    
                case 'chebyshev'
                    seq = ChaosEncryption.chebyshev_map(...
                        obj.initial_conditions.x0, ...
                        obj.parameters.k, total_N);
                    
                case 'henon'
                    [seq, ~] = ChaosEncryption.henon_map(...
                        obj.initial_conditions.x0, ...
                        obj.initial_conditions.y0, ...
                        obj.parameters.a, obj.parameters.b, total_N);
            end
            
            % 去除瞬態
            sequence = seq(remove_N+1:end);
        end
        
        function [encrypted_data, chaos_seq] = encrypt_data(obj, data, method)
            % 加密數據
            if nargin < 3
                method = 'bit_xor';
            end
            
            N = length(data);
            chaos_seq = obj.generate_sequence(N);
            
            switch method
                case 'bit_xor'
                    % 二進制異或加密
                    if islogical(data)
                        chaos_bits = ChaosEncryption.generate_chaos_bits(chaos_seq);
                        encrypted_data = ChaosEncryption.chaos_encrypt_bits(data, chaos_bits);
                    else
                        error('Bit XOR method requires binary input data');
                    end
                    
                case 'phase_rotation'
                    % 相位旋轉加密 (用於OFDM符號)
                    encrypted_data = data .* exp(1j * 2 * pi * chaos_seq);
                    
                case 'subcarrier_permutation'
                    % 子載波置換加密
                    [~, perm_idx] = sort(chaos_seq);
                    encrypted_data = data(perm_idx);
                    
                case 'amplitude_modulation'
                    % 幅度調製加密
                    scaling_factors = 0.5 + chaos_seq; % 縮放因子在0.5-1.5之間
                    encrypted_data = data .* scaling_factors;
                    
                otherwise
                    error('Unknown encryption method');
            end
        end
        
        function decrypted_data = decrypt_data(obj, encrypted_data, chaos_seq, method)
            % 解密數據
            if nargin < 4
                method = 'bit_xor';
            end
            
            switch method
                case 'bit_xor'
                    chaos_bits = ChaosEncryption.generate_chaos_bits(chaos_seq);
                    decrypted_data = ChaosEncryption.chaos_decrypt_bits(encrypted_data, chaos_bits);
                    
                case 'phase_rotation'
                    decrypted_data = encrypted_data .* exp(-1j * 2 * pi * chaos_seq);
                    
                case 'subcarrier_permutation'
                    [~, perm_idx] = sort(chaos_seq);
                    [~, inv_perm_idx] = sort(perm_idx);
                    decrypted_data = encrypted_data(inv_perm_idx);
                    
                case 'amplitude_modulation'
                    scaling_factors = 0.5 + chaos_seq;
                    decrypted_data = encrypted_data ./ scaling_factors;
            end
        end
        
        function analyze_chaos_properties(obj, N)
            % 分析混沌序列特性
            sequence = obj.generate_sequence(N);
            
            fprintf('混沌序列特性分析 (%s映射):\n', obj.chaos_type);
            fprintf('  序列長度: %d\n', N);
            fprintf('  均值: %.6f\n', mean(sequence));
            fprintf('  方差: %.6f\n', var(sequence));
            fprintf('  自相關 (lag=1): %.6f\n', autocorr(sequence, 1));
            
            % 繪製特性圖
            figure('Position', [100, 100, 1200, 800]);
            
            subplot(2, 3, 1);
            plot(sequence(1:min(1000, N)), 'b-', 'LineWidth', 1);
            title('混沌序列時域波形');
            xlabel('樣本索引');
            ylabel('幅度');
            grid on;
            
            subplot(2, 3, 2);
            hist(sequence, 50);
            title('混沌序列直方圖');
            xlabel('幅度');
            ylabel('頻數');
            grid on;
            
            subplot(2, 3, 3);
            plot(sequence(1:end-1), sequence(2:end), 'b.');
            title('混沌吸引子');
            xlabel('x(n)');
            ylabel('x(n+1)');
            grid on;
            axis equal;
            
            subplot(2, 3, 4);
            autocorr(sequence, 50);
            title('自相關函數');
            grid on;
            
            subplot(2, 3, 5);
            [pxx, f] = pwelch(sequence - mean(sequence), [], [], [], 1);
            semilogy(f, pxx, 'b-', 'LineWidth', 1);
            title('功率譜密度');
            xlabel('歸一化頻率');
            ylabel('PSD');
            grid on;
            
            % Lyapunov指數估計
            subplot(2, 3, 6);
            lambda = estimate_lyapunov_exponent(sequence);
            bar(1, lambda);
            title(sprintf('Lyapunov指數估計: %.4f', lambda));
            ylabel('Lyapunov指數');
            grid on;
            
            sgtitle(sprintf('%s混沌序列特性分析', upper(obj.chaos_type)));
        end
    end
end

function lambda = estimate_lyapunov_exponent(sequence)
    % 估計Lyapunov指數 (簡化方法)
    N = length(sequence);
    divergence = zeros(1, N-1);
    
    for i = 1:N-1
        divergence(i) = abs(sequence(i+1) - sequence(i));
    end
    
    lambda = mean(log(divergusion(divergence > 0) + eps));
end

2. OFDM系統基礎實現

2.1 OFDM收發器類

classdef OFDMSystem
    % OFDM系統基類
    
    properties
        Nfft               % FFT點數
        Ncp                % 循環前綴長度
        Nsc                % 子載波數量
        modulation_order   % 調製階數
        sampling_freq      % 採樣頻率
        symbol_duration    % 符號持續時間
        subcarrier_spacing % 子載波間隔
        pilot_pattern      % 導頻模式
        equalizer_type     % 均衡器類型
    end
    
    methods
        function obj = OFDMSystem(config)
            % 構造函數
            obj.Nfft = config.Nfft;
            obj.Ncp = config.Ncp;
            obj.Nsc = config.Nsc;
            obj.modulation_order = config.modulation_order;
            obj.sampling_freq = config.sampling_freq;
            obj.symbol_duration = (obj.Nfft + obj.Ncp) / obj.sampling_freq;
            obj.subcarrier_spacing = obj.sampling_freq / obj.Nfft;
        end
        
        function modulated_symbols = modulate(obj, data_bits)
            % 調製數據比特
            switch obj.modulation_order
                case 1 % BPSK
                    modulated_symbols = 1 - 2 * data_bits;
                    
                case 2 % QPSK
                    reshaped_bits = reshape(data_bits, 2, []);
                    symbols = (1 - 2 * reshaped_bits(1,:)) + ...
                              1j * (1 - 2 * reshaped_bits(2,:));
                    modulated_symbols = symbols / sqrt(2);
                    
                case 4 % 16QAM
                    reshaped_bits = reshape(data_bits, 4, []);
                    real_part = 2*(1-2*reshaped_bits(1,:)) .* ...
                               (1+2*reshaped_bits(2,:));
                    imag_part = 2*(1-2*reshaped_bits(3,:)) .* ...
                               (1+2*reshaped_bits(4,:));
                    modulated_symbols = (real_part + 1j * imag_part) / sqrt(10);
                    
                otherwise
                    error('Unsupported modulation order');
            end
        end
        
        function data_bits = demodulate(obj, received_symbols)
            % 解調接收符號
            switch obj.modulation_order
                case 1 % BPSK
                    data_bits = real(received_symbols) < 0;
                    
                case 2 % QPSK
                    real_bits = real(received_symbols) < 0;
                    imag_bits = imag(received_symbols) < 0;
                    data_bits = [real_bits; imag_bits];
                    data_bits = data_bits(:)';
                    
                case 4 % 16QAM
                    % 簡化解調 - 實際應用中應該使用最大似然檢測
                    real_vals = real(received_symbols);
                    imag_vals = imag(received_symbols);
                    
                    real_bits = zeros(2, length(real_vals));
                    imag_bits = zeros(2, length(imag_vals));
                    
                    % 判決區域
                    real_bits(1,:) = real_vals < 0;
                    real_bits(2,:) = abs(real_vals) > 2/sqrt(10);
                    
                    imag_bits(1,:) = imag_vals < 0;
                    imag_bits(2,:) = abs(imag_vals) > 2/sqrt(10);
                    
                    data_bits = [real_bits; imag_bits];
                    data_bits = data_bits(:)';
                    
                otherwise
                    error('Unsupported modulation order');
            end
        end
        
        function ofdm_symbol = ifft_modulate(obj, freq_symbols)
            % IFFT調製
            % 確保輸入符號長度正確
            if length(freq_symbols) ~= obj.Nsc
                error('Number of subcarriers does not match');
            end
            
            % 創建完整的FFT向量 (包含直流和鏡像載波)
            full_spectrum = zeros(1, obj.Nfft);
            
            % 放置數據子載波 (居中放置)
            start_idx = floor((obj.Nfft - obj.Nsc) / 2) + 1;
            end_idx = start_idx + obj.Nsc - 1;
            full_spectrum(start_idx:end_idx) = freq_symbols;
            
            % IFFT
            time_signal = ifft(full_spectrum, obj.Nfft);
            
            % 添加循環前綴
            cp = time_signal(end-obj.Ncp+1:end);
            ofdm_symbol = [cp, time_signal];
        end
        
        function freq_symbols = fft_demodulate(obj, time_signal)
            % FFT解調
            % 移除循環前綴
            if length(time_signal) ~= obj.Nfft + obj.Ncp
                error('Invalid OFDM symbol length');
            end
            
            symbol_without_cp = time_signal(obj.Ncp+1:end);
            
            % FFT
            full_spectrum = fft(symbol_without_cp, obj.Nfft);
            
            % 提取數據子載波
            start_idx = floor((obj.Nfft - obj.Nsc) / 2) + 1;
            end_idx = start_idx + obj.Nsc - 1;
            freq_symbols = full_spectrum(start_idx:end_idx);
        end
        
        function [tx_signal, tx_symbols] = transmit(obj, data_bits)
            % 完整的OFDM發射流程
            num_bits_per_symbol = obj.Nsc * log2(obj.modulation_order);
            num_symbols = ceil(length(data_bits) / num_bits_per_symbol);
            
            % 零填充
            padded_bits = [data_bits, zeros(1, num_symbols * num_bits_per_symbol - length(data_bits))];
            
            tx_signal = [];
            tx_symbols = [];
            
            for sym = 1:num_symbols
                % 提取當前符號的比特
                start_bit = (sym-1) * num_bits_per_symbol + 1;
                end_bit = sym * num_bits_per_symbol;
                symbol_bits = padded_bits(start_bit:end_bit);
                
                % 調製
                modulated_data = obj.modulate(symbol_bits);
                tx_symbols = [tx_symbols, modulated_data];
                
                % OFDM調製
                ofdm_sym = obj.ifft_modulate(modulated_data);
                tx_signal = [tx_signal, ofdm_sym];
            end
        end
        
        function [received_bits, eq_symbols] = receive(obj, rx_signal, channel, noise_variance)
            % 完整的OFDM接收流程
            symbol_length = obj.Nfft + obj.Ncp;
            num_symbols = floor(length(rx_signal) / symbol_length);
            
            received_bits = [];
            eq_symbols = [];
            
            for sym = 1:num_symbols
                % 提取當前OFDM符號
                start_sample = (sym-1) * symbol_length + 1;
                end_sample = sym * symbol_length;
                ofdm_symbol = rx_signal(start_sample:end_sample);
                
                % OFDM解調
                freq_symbols = obj.fft_demodulate(ofdm_symbol);
                
                % 信道均衡 (簡化)
                if nargin >= 3 && ~isempty(channel)
                    % 頻域均衡
                    H = fft(channel, obj.Nfft);
                    start_idx = floor((obj.Nfft - obj.Nsc) / 2) + 1;
                    end_idx = start_idx + obj.Nsc - 1;
                    H_data = H(start_idx:end_idx);
                    
                    % ZF均衡
                    eq_freq_symbols = freq_symbols ./ H_data;
                else
                    eq_freq_symbols = freq_symbols;
                end
                
                eq_symbols = [eq_symbols, eq_freq_symbols];
                
                % 解調
                symbol_bits = obj.demodulate(eq_freq_symbols);
                received_bits = [received_bits, symbol_bits];
            end
        end
    end
end

3. 混沌加密OFDM系統

3.1 集成混沌加密的OFDM系統

classdef ChaosEncryptedOFDM < OFDMSystem
    % 基於混沌加密的OFDM系統
    
    properties
        chaos_system       % 混沌系統
        encryption_method  % 加密方法
        encryption_key     % 加密密鑰
    end
    
    methods
        function obj = ChaosEncryptedOFDM(config)
            % 構造函數
            obj = obj@OFDMSystem(config);
            
            if isfield(config, 'chaos_system')
                obj.chaos_system = config.chaos_system;
            else
                % 默認使用Logistic映射
                obj.chaos_system = EnhancedChaosSystem('logistic', 'r', 3.99, 'x0', 0.5);
            end
            
            if isfield(config, 'encryption_method')
                obj.encryption_method = config.encryption_method;
            else
                obj.encryption_method = 'phase_rotation';
            end
            
            % 生成加密密鑰
            obj.encryption_key = obj.generate_encryption_key();
        end
        
        function key = generate_encryption_key(obj)
            % 生成加密密鑰
            % 基於混沌序列生成加密密鑰
            key.chaos_sequence = obj.chaos_system.generate_sequence(1000);
            key.method = obj.encryption_method;
            key.timestamp = now;
        end
        
        function [encrypted_symbols, chaos_seq] = encrypt_ofdm_symbols(obj, symbols)
            % 加密OFDM符號
            N = length(symbols);
            chaos_seq = obj.chaos_system.generate_sequence(N);
            
            encrypted_symbols = obj.chaos_system.encrypt_data(...
                symbols, chaos_seq, obj.encryption_method);
        end
        
        function decrypted_symbols = decrypt_ofdm_symbols(obj, encrypted_symbols, chaos_seq)
            % 解密OFDM符號
            decrypted_symbols = obj.chaos_system.decrypt_data(...
                encrypted_symbols, chaos_seq, obj.encryption_method);
        end
        
        function [tx_signal, encryption_info] = transmit_encrypted(obj, data_bits)
            % 發射加密的OFDM信號
            num_bits_per_symbol = obj.Nsc * log2(obj.modulation_order);
            num_symbols = ceil(length(data_bits) / num_bits_per_symbol);
            
            % 零填充
            padded_bits = [data_bits, zeros(1, num_symbols * num_bits_per_symbol - length(data_bits))];
            
            tx_signal = [];
            all_chaos_sequences = [];
            
            for sym = 1:num_symbols
                % 提取當前符號的比特
                start_bit = (sym-1) * num_bits_per_symbol + 1;
                end_bit = sym * num_bits_per_symbol;
                symbol_bits = padded_bits(start_bit:end_bit);
                
                % 調製
                modulated_data = obj.modulate(symbol_bits);
                
                % 混沌加密
                [encrypted_data, chaos_seq] = obj.encrypt_ofdm_symbols(modulated_data);
                all_chaos_sequences = [all_chaos_sequences; chaos_seq];
                
                % OFDM調製
                ofdm_sym = obj.ifft_modulate(encrypted_data);
                tx_signal = [tx_signal, ofdm_sym];
            end
            
            encryption_info.chaos_sequences = all_chaos_sequences;
            encryption_info.method = obj.encryption_method;
        end
        
        function received_bits = receive_encrypted(obj, rx_signal, encryption_info, channel, noise_variance)
            % 接收並解密OFDM信號
            symbol_length = obj.Nfft + obj.Ncp;
            num_symbols = floor(length(rx_signal) / symbol_length);
            
            if num_symbols ~= size(encryption_info.chaos_sequences, 1)
                error('Number of symbols does not match encryption info');
            end
            
            received_bits = [];
            
            for sym = 1:num_symbols
                % 提取當前OFDM符號
                start_sample = (sym-1) * symbol_length + 1;
                end_sample = sym * symbol_length;
                ofdm_symbol = rx_signal(start_sample:end_sample);
                
                % OFDM解調
                freq_symbols = obj.fft_demodulate(ofdm_symbol);
                
                % 信道均衡
                if nargin >= 4 && ~isempty(channel)
                    H = fft(channel, obj.Nfft);
                    start_idx = floor((obj.Nfft - obj.Nsc) / 2) + 1;
                    end_idx = start_idx + obj.Nsc - 1;
                    H_data = H(start_idx:end_idx);
                    eq_freq_symbols = freq_symbols ./ H_data;
                else
                    eq_freq_symbols = freq_symbols;
                end
                
                % 混沌解密
                chaos_seq = encryption_info.chaos_sequences(sym, :);
                decrypted_symbols = obj.decrypt_ofdm_symbols(eq_freq_symbols, chaos_seq);
                
                % 解調
                symbol_bits = obj.demodulate(decrypted_symbols);
                received_bits = [received_bits, symbol_bits];
            end
        end
        
        function analyze_security_performance(obj, data_length)
            % 分析安全性能
            fprintf('=== 混沌加密OFDM系統安全性能分析 ===\n\n');
            
            % 生成測試數據
            test_bits = randi([0 1], 1, data_length);
            
            % 原始傳輸
            [tx_signal_plain, ~] = obj.transmit(test_bits);
            
            % 加密傳輸
            [tx_signal_enc, enc_info] = obj.transmit_encrypted(test_bits);
            
            % 分析安全性
            analyze_encryption_security(tx_signal_plain, tx_signal_enc, test_bits, obj, enc_info);
        end
    end
end

function analyze_encryption_security(plain_signal, enc_signal, original_bits, ofdm_system, enc_info)
    % 分析加密安全性
    
    figure('Position', [100, 100, 1400, 1000]);
    
    % 時域信號比較
    subplot(3, 3, 1);
    plot(real(plain_signal(1:1000)), 'b-', 'LineWidth', 1.5, 'DisplayName', '明文');
    hold on;
    plot(real(enc_signal(1:1000)), 'r-', 'LineWidth', 1.5, 'DisplayName', '密文');
    title('時域信號比較');
    xlabel('樣本索引');
    ylabel('幅度');
    legend;
    grid on;
    
    % 頻域比較
    subplot(3, 3, 2);
    N = min(length(plain_signal), 1024);
    f_plain = abs(fft(plain_signal(1:N)));
    f_enc = abs(fft(enc_signal(1:N)));
    freq = (0:N-1) / N * ofdm_system.sampling_freq / 1e6;
    plot(freq, 10*log10(f_plain), 'b-', 'DisplayName', '明文');
    hold on;
    plot(freq, 10*log10(f_enc), 'r-', 'DisplayName', '密文');
    title('頻域特性比較');
    xlabel('頻率 (MHz)');
    ylabel('功率譜密度 (dB)');
    legend;
    grid on;
    
    % 星座圖比較
    subplot(3, 3, 3);
    % 提取第一個OFDM符號的頻域數據
    symbol_len = ofdm_system.Nfft + ofdm_system.Ncp;
    plain_freq = ofdm_system.fft_demodulate(plain_signal(1:symbol_len));
    enc_freq = ofdm_system.fft_demodulate(enc_signal(1:symbol_len));
    
    plot(real(plain_freq), imag(plain_freq), 'bo', 'DisplayName', '明文');
    hold on;
    plot(real(enc_freq), imag(enc_freq), 'rx', 'DisplayName', '密文');
    title('星座圖比較');
    xlabel('同相分量');
    ylabel('正交分量');
    legend;
    grid on;
    axis equal;
    
    % 自相關分析
    subplot(3, 3, 4);
    [acf_plain, lags] = xcorr(plain_signal(1:1000), 100, 'coeff');
    [acf_enc, ~] = xcorr(enc_signal(1:1000), 100, 'coeff');
    plot(lags, abs(acf_plain), 'b-', 'DisplayName', '明文');
    hold on;
    plot(lags, abs(acf_enc), 'r-', 'DisplayName', '密文');
    title('自相關函數');
    xlabel('延遲');
    ylabel('自相關');
    legend;
    grid on;
    
    % 互相關分析
    subplot(3, 3, 5);
    [ccf, lags] = xcorr(plain_signal(1:1000), enc_signal(1:1000), 100, 'coeff');
    plot(lags, abs(ccf), 'g-', 'LineWidth', 1.5);
    title('明文-密文互相關');
    xlabel('延遲');
    ylabel('互相關');
    grid on;
    
    % 熵分析
    subplot(3, 3, 6);
    entropy_plain = calculate_signal_entropy(plain_signal);
    entropy_enc = calculate_signal_entropy(enc_signal);
    bar([1, 2], [entropy_plain, entropy_enc]);
    set(gca, 'XTickLabel', {'明文', '密文'});
    ylabel('信息熵');
    title('信號信息熵比較');
    grid on;
    
    % 密鑰敏感性分析
    subplot(3, 3, 7);
    % 使用稍微不同的密鑰解密
    wrong_key = enc_info;
    wrong_key.chaos_sequences(1, :) = wrong_key.chaos_sequences(1, :) + 1e-10;
    
    try
        decrypted_wrong = ofdm_system.receive_encrypted(enc_signal, wrong_key);
        ber_wrong = sum(decrypted_wrong(1:length(original_bits)) ~= original_bits) / length(original_bits);
    catch
        ber_wrong = 0.5; % 完全解密失敗
    end
    
    % 正確解密
    decrypted_correct = ofdm_system.receive_encrypted(enc_signal, enc_info);
    ber_correct = sum(decrypted_correct(1:length(original_bits)) ~= original_bits) / length(original_bits);
    
    bar([1, 2], [ber_correct, ber_wrong]);
    set(gca, 'XTickLabel', {'正確密鑰', '錯誤密鑰'});
    ylabel('誤碼率');
    title('密鑰敏感性分析');
    grid on;
    
    % 加密方法比較
    subplot(3, 3, 8);
    methods = {'phase_rotation', 'subcarrier_permutation', 'amplitude_modulation'};
    ber_values = zeros(1, length(methods));
    
    for i = 1:length(methods)
        temp_system = ofdm_system;
        temp_system.encryption_method = methods{i};
        [enc_sig_temp, enc_info_temp] = temp_system.transmit_encrypted(original_bits);
        dec_bits_temp = temp_system.receive_encrypted(enc_sig_temp, enc_info_temp);
        ber_values(i) = sum(dec_bits_temp(1:length(original_bits)) ~= original_bits) / length(original_bits);
    end
    
    bar(ber_values);
    set(gca, 'XTickLabel', {'相位', '置換', '幅度'});
    ylabel('解密BER');
    title('加密方法性能比較');
    grid on;
    
    % 安全性指標總結
    subplot(3, 3, 9);
    security_metrics = calculate_security_metrics(plain_signal, enc_signal);
    bar(1:length(security_metrics), cell2mat(security_metrics(2:2:end)));
    set(gca, 'XTickLabel', security_metrics(1:2:end));
    ylabel('指標值');
    title('安全性指標總結');
    grid on;
    rotateXLabels(gca, 45);
    
    sgtitle('混沌加密OFDM系統安全性能分析');
end

function entropy = calculate_signal_entropy(signal)
    % 計算信號的信息熵
    [counts, ~] = hist(real(signal), 50);
    prob = counts / sum(counts);
    prob = prob(prob > 0); % 移除零概率
    entropy = -sum(prob .* log2(prob));
end

function metrics = calculate_security_metrics(plain_signal, enc_signal)
    % 計算安全性指標
    
    % 相關性
    correlation = max(abs(xcorr(plain_signal, enc_signal, 'coeff')));
    
    % 密鑰空間大小 (估計)
    key_space = 1e6; % 簡化估計
    
    % 敏感性
    diff_signal = plain_signal - enc_signal;
    sensitivity = mean(abs(diff_signal).^2) / mean(abs(plain_signal).^2);
    
    metrics = {
        '相關性', correlation, ...
        '密鑰空間', key_space, ...
        '敏感性', sensitivity, ...
        '明文熵', calculate_signal_entropy(plain_signal), ...
        '密文熵', calculate_signal_entropy(enc_signal)
    };
end

4. 完整的主程序與性能評估

4.1 主程序實現

function main_chaos_encrypted_ofdm()
    % 混沌加密OFDM系統主程序
    
    fprintf('=== 基於混沌加密的OFDM系統仿真 ===\n\n');
    
    % 系統參數配置
    ofdm_config.Nfft = 64;
    ofdm_config.Ncp = 16;
    ofdm_config.Nsc = 52;
    ofdm_config.modulation_order = 2; % QPSK
    ofdm_config.sampling_freq = 20e6;
    
    % 混沌系統配置
    chaos_system = EnhancedChaosSystem('logistic', 'r', 3.99, 'x0', 0.5);
    
    % 創建混沌加密OFDM系統
    encrypted_ofdm = ChaosEncryptedOFDM(ofdm_config);
    encrypted_ofdm.chaos_system = chaos_system;
    encrypted_ofdm.encryption_method = 'phase_rotation';
    
    fprintf('系統參數:\n');
    fprintf('  FFT點數: %d\n', encrypted_ofdm.Nfft);
    fprintf('  子載波數: %d\n', encrypted_ofdm.Nsc);
    fprintf('  循環前綴: %d\n', encrypted_ofdm.Ncp);
    fprintf('  調製方式: %s\n', get_modulation_name(encrypted_ofdm.modulation_order));
    fprintf('  加密方法: %s\n', encrypted_ofdm.encryption_method);
    fprintf('  混沌系統: %s\n', encrypted_ofdm.chaos_system.chaos_type);
    
    % 生成測試數據
    data_length = 10000;
    original_bits = randi([0 1], 1, data_length);
    
    fprintf('\n測試數據: %d bits\n', data_length);
    
    % 性能比較測試
    compare_performance(encrypted_ofdm, original_bits);
    
    % 安全性分析
    fprintf('\n進行安全性分析...\n');
    encrypted_ofdm.analyze_security_performance(1000);
    
    % 魯棒性測試
    fprintf('\n進行魯棒性測試...\n');
    test_robustness(encrypted_ofdm, original_bits);
    
    fprintf('\n=== 仿真完成 ===\n');
end

function compare_performance(ofdm_system, original_bits)
    % 性能比較:加密 vs 未加密
    
    fprintf('\n=== 性能比較分析 ===\n');
    
    % 未加密傳輸
    fprintf('未加密傳輸...\n');
    [tx_signal_plain, tx_symbols_plain] = ofdm_system.transmit(original_bits);
    
    % 加密傳輸
    fprintf('加密傳輸...\n');
    [tx_signal_enc, enc_info] = ofdm_system.transmit_encrypted(original_bits);
    
    % AWGN信道測試
    snr_values = 0:2:20;
    ber_plain = zeros(size(snr_values));
    ber_enc = zeros(size(snr_values));
    
    for i = 1:length(snr_values)
        snr = snr_values(i);
        
        % 未加密系統
        rx_signal_plain = awgn(tx_signal_plain, snr, 'measured');
        received_bits_plain = ofdm_system.receive(rx_signal_plain);
        ber_plain(i) = sum(received_bits_plain(1:length(original_bits)) ~= original_bits) / length(original_bits);
        
        % 加密系統
        rx_signal_enc = awgn(tx_signal_enc, snr, 'measured');
        received_bits_enc = ofdm_system.receive_encrypted(rx_signal_enc, enc_info);
        ber_enc(i) = sum(received_bits_enc(1:length(original_bits)) ~= original_bits) / length(original_bits);
    end
    
    % 繪製性能曲線
    figure('Position', [100, 100, 1200, 800]);
    
    subplot(2, 2, 1);
    semilogy(snr_values, ber_plain, 'bo-', 'LineWidth', 2, 'MarkerSize', 8, 'DisplayName', '未加密');
    hold on;
    semilogy(snr_values, ber_enc, 'rs-', 'LineWidth', 2, 'MarkerSize', 8, 'DisplayName', '加密');
    xlabel('SNR (dB)');
    ylabel('誤碼率 (BER)');
    title('加密 vs 未加密系統性能比較');
    legend;
    grid on;
    
    % 計算性能損失
    performance_loss = ber_enc - ber_plain;
    subplot(2, 2, 2);
    plot(snr_values, performance_loss, 'g^-', 'LineWidth', 2, 'MarkerSize', 8);
    xlabel('SNR (dB)');
    ylabel('BER性能損失');
    title('加密引入的性能損失');
    grid on;
    
    % 複雜度分析
    subplot(2, 2, 3);
    complexity_metrics = analyze_complexity(ofdm_system, length(original_bits));
    bar(cell2mat(complexity_metrics(2:2:end)));
    set(gca, 'XTickLabel', complexity_metrics(1:2:end));
    ylabel('相對複雜度');
    title('系統複雜度分析');
    grid on;
    
    % 吞吐量分析
    subplot(2, 2, 4);
    throughput = calculate_throughput(ber_plain, ber_enc, snr_values, ofdm_system);
    plot(snr_values, throughput.plain, 'bo-', 'DisplayName', '未加密');
    hold on;
    plot(snr_values, throughput.encrypted, 'rs-', 'DisplayName', '加密');
    xlabel('SNR (dB)');
    ylabel('有效吞吐量 (Mbps)');
    title('系統吞吐量比較');
    legend;
    grid on;
    
    sgtitle('混沌加密OFDM系統性能分析');
end

function test_robustness(ofdm_system, original_bits)
    % 魯棒性測試
    
    fprintf('進行系統魯棒性測試...\n');
    
    % 測試不同信道條件
    channel_types = {'AWGN', 'Rayleigh', 'Rician'};
    robustness_results = cell(length(channel_types), 1);
    
    figure('Position', [100, 100, 1200, 600]);
    
    for i = 1:length(channel_types)
        channel_type = channel_types{i};
        fprintf('測試信道: %s\n', channel_type);
        
        % 生成加密信號
        [tx_signal, enc_info] = ofdm_system.transmit_encrypted(original_bits);
        
        % 應用不同信道
        rx_signal = apply_channel(tx_signal, channel_type, 10); % SNR = 10dB
        
        % 解密接收
        received_bits = ofdm_system.receive_encrypted(rx_signal, enc_info);
        ber = sum(received_bits(1:length(original_bits)) ~= original_bits) / length(original_bits);
        
        robustness_results{i} = struct('channel', channel_type, 'ber', ber);
        
        % 繪製星座圖
        subplot(2, 3, i);
        symbol_len = ofdm_system.Nfft + ofdm_system.Ncp;
        rx_freq = ofdm_system.fft_demodulate(rx_signal(1:symbol_len));
        plot(real(rx_freq), imag(rx_freq), 'b.');
        title(sprintf('%s信道 - BER: %.4f', channel_type, ber));
        xlabel('同相分量');
        ylabel('正交分量');
        grid on;
        axis equal;
    end
    
    % 密鑰錯誤敏感性測試
    subplot(2, 3, 4);
    test_key_sensitivity(ofdm_system, original_bits);
    
    % 參數敏感性測試
    subplot(2, 3, 5);
    test_parameter_sensitivity(ofdm_system, original_bits);
    
    % 綜合魯棒性評分
    subplot(2, 3, 6);
    overall_robustness = evaluate_overall_robustness(robustness_results);
    bar(overall_robustness.scores);
    set(gca, 'XTickLabel', overall_robustness.metrics);
    ylabel('評分 (0-10)');
    title('系統魯棒性綜合評分');
    grid on;
    rotateXLabels(gca, 45);
    
    sgtitle('混沌加密OFDM系統魯棒性測試');
end

function name = get_modulation_name(order)
    % 獲取調製方式名稱
    switch order
        case 1
            name = 'BPSK';
        case 2
            name = 'QPSK';
        case 4
            name = '16QAM';
        otherwise
            name = sprintf('%d-QAM', 2^order);
    end
end

function rx_signal = apply_channel(tx_signal, channel_type, snr)
    % 應用信道模型
    switch channel_type
        case 'AWGN'
            rx_signal = awgn(tx_signal, snr, 'measured');
            
        case 'Rayleigh'
            % 瑞利衰落信道
            channel = (randn(1, 6) + 1j * randn(1, 6)) / sqrt(2);
            rx_signal = conv(tx_signal, channel, 'same');
            rx_signal = awgn(rx_signal, snr, 'measured');
            
        case 'Rician'
            % 萊斯衰落信道
            K = 3; % K因子
            direct_path = sqrt(K/(K+1));
            scattered = sqrt(1/(2*(K+1))) * (randn(1, 4) + 1j * randn(1, 4));
            channel = [direct_path, scattered];
            rx_signal = conv(tx_signal, channel, 'same');
            rx_signal = awgn(rx_signal, snr, 'measured');
    end
end

function complexity = analyze_complexity(ofdm_system, data_length)
    % 分析系統複雜度
    base_operations = data_length * log2(ofdm_system.Nfft); % FFT複雜度基準
    
    % 加密操作複雜度估計
    switch ofdm_system.encryption_method
        case 'phase_rotation'
            encryption_ops = data_length * 2; % 複數乘法
        case 'subcarrier_permutation'
            encryption_ops = data_length * log2(data_length); % 排序複雜度
        case 'amplitude_modulation'
            encryption_ops = data_length; % 實數乘法
        otherwise
            encryption_ops = data_length;
    end
    
    total_ops = base_operations + encryption_ops;
    
    complexity = {
        'FFT運算', base_operations, ...
        '加密運算', encryption_ops, ...
        '總運算量', total_ops, ...
        '複雜度增加', encryption_ops / base_operations
    };
end

function throughput = calculate_throughput(ber_plain, ber_enc, snr_values, ofdm_system)
    % 計算系統吞吐量
    bits_per_symbol = ofdm_system.Nsc * log2(ofdm_system.modulation_order);
    symbols_per_second = ofdm_system.sampling_freq / (ofdm_system.Nfft + ofdm_system.Ncp);
    
    throughput.plain = (1 - ber_plain) * bits_per_symbol * symbols_per_second / 1e6; % Mbps
    throughput.encrypted = (1 - ber_enc) * bits_per_symbol * symbols_per_second / 1e6; % Mbps
end

function test_key_sensitivity(ofdm_system, original_bits)
    % 測試密鑰敏感性
    key_errors = logspace(-15, -5, 10);
    ber_sensitivity = zeros(size(key_errors));
    
    [tx_signal, enc_info] = ofdm_system.transmit_encrypted(original_bits);
    
    for i = 1:length(key_errors)
        wrong_info = enc_info;
        wrong_info.chaos_sequences = wrong_info.chaos_sequences + key_errors(i);
        
        try
            received_bits = ofdm_system.receive_encrypted(tx_signal, wrong_info);
            ber_sensitivity(i) = sum(received_bits(1:length(original_bits)) ~= original_bits) / length(original_bits);
        catch
            ber_sensitivity(i) = 0.5;
        end
    end
    
    semilogx(key_errors, ber_sensitivity, 'ro-', 'LineWidth', 2);
    xlabel('密鑰誤差');
    ylabel('誤碼率');
    title('密鑰敏感性測試');
    grid on;
end

function test_parameter_sensitivity(ofdm_system, original_bits)
    % 測試參數敏感性
    param_errors = linspace(0, 0.1, 10);
    ber_sensitivity = zeros(size(param_errors));
    
    for i = 1:length(param_errors)
        % 創建參數錯誤的系統
        wrong_system = ofdm_system;
        wrong_system.chaos_system.parameters.r = wrong_system.chaos_system.parameters.r + param_errors(i);
        
        [tx_signal, enc_info] = wrong_system.transmit_encrypted(original_bits);
        
        try
            % 用正確系統解密
            received_bits = ofdm_system.receive_encrypted(tx_signal, enc_info);
            ber_sensitivity(i) = sum(received_bits(1:length(original_bits)) ~= original_bits) / length(original_bits);
        catch
            ber_sensitivity(i) = 0.5;
        end
    end
    
    plot(param_errors, ber_sensitivity, 'bo-', 'LineWidth', 2);
    xlabel('參數誤差');
    ylabel('誤碼率');
    title('參數敏感性測試');
    grid on;
end

function robustness = evaluate_overall_robustness(results)
    % 評估整體魯棒性
    metrics = {'信道適應性', '密鑰敏感性', '參數魯棒性', '噪聲免疫性'};
    scores = [8.5, 9.2, 7.8, 8.0]; % 示例評分
    
    robustness.metrics = metrics;
    robustness.scores = scores;
    robustness.average_score = mean(scores);
end

% 運行主程序
main_chaos_encrypted_ofdm();

參考代碼 基於混沌加密的ofdm碼 www.youwenfan.com/contentcnl/80081.html

總結

主要特點:

  1. 多種混沌系統:Logistic、Tent、Chebyshev、Henon映射
  2. 多種加密方法:相位旋轉、子載波置換、幅度調製
  3. 完整的OFDM系統:包含調製解調、FFT/IFFT、循環前綴
  4. 安全性分析:相關性分析、熵分析、密鑰敏感性
  5. 性能評估:BER分析、吞吐量計算、複雜度分析

技術優勢:

  • 高安全性:混沌系統的初值敏感性和隨機性
  • 物理層安全:在物理層實現加密,增強系統安全性
  • 靈活性:支持多種混沌系統和加密方法
  • 實用性:可與現有OFDM系統兼容

應用價值:

  • 為無線通信系統提供物理層安全解決方案
  • 適用於5G/6G、WiFi、LTE等OFDM系統
  • 支持安全性與性能的權衡分析
  • 為通信安全研究提供完整仿真平台