忍者ブログ
Flex,Java,Html など、調べた事のメモ帳です。 間違ってたらゴメンなさい。
×

[PR]上記の広告は3ヶ月以上新規記事投稿のないブログに表示されています。新しい記事を書く事で広告が消えます。

秘密鍵暗号化方式で暗号化

javax.crypto パッケージを使って、文字列を暗号化して同じ鍵を使用して復号化します。 秘密鍵の生成には KeyGenerator の generateKey() を使用し、暗号化、復号化には Cipher の doFinal を使用します。

以下にアルゴリズムに AES を使用した場合の暗号化、復号化の実装例を書きます。


	

コード記述例

public static void main(String[] args) {
    try {
        SecretKey key = KeyGenerator.getInstance("AES").generateKey();
        Cipher aes = Cipher.getInstance("AES");
        HexDumpEncoder enc = new HexDumpEncoder();
        byte[] text = "暗号化テスト".getBytes();
        System.out.println(enc.encode(text));
 
        // 暗号化
        aes.init(Cipher.ENCRYPT_MODE, key);
        byte[] encryptText = aes.doFinal(text);
        System.out.println(enc.encode(encryptText));
 
        // 複合化
        aes.init(Cipher.DECRYPT_MODE, key);
        byte[] decryptText = aes.doFinal(encryptText);
        System.out.println(enc.encode(decryptText));
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 

 

出力結果


上から順に 元テキスト → 暗号化配列 → 復元されたテキスト です。

	
0000: 88 C3 8D 86 89 BB 83 65 83 58 83 67
0000: EF A2 F1 18 3A B6 7D 16 7B 89 F9 E3 27 4B 48 F4 ....:.......'KH.
0000: 88 C3 8D 86 89 BB 83 65 83 58 83 67
 
この記事にコメントする
name
title
color
mail
URL
comment
pass   Vodafone絵文字 i-mode絵文字 Ezweb絵文字
secret (チェックを入れると管理人だけに表示できます)
ブログランキング
にほんブログ村 IT技術ブログ IT技術メモへ
 
カレンダー
03 2024/04 05
S M T W T F S
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
人気ブログランキング
ブログランキング ブログランキング
最新TB
ブログ内検索
PR
ATOM  
ATOM 
RSS  
RSS 
Copyright ©   プログラムメモ   All Rights Reserved
Design by MMIT  Powered by NINJA TOOLS
忍者ブログ [PR]