JavaSE RSA暗号 の Java8 版。RSA暗号の基礎についてはそちらを参考にすること

秘密鍵と公開鍵の作成 (Openssl)

https://github.com/kagyuu/RSAExam/blob/master/RSAExam/src/main/resources/create_keys.sh

#!/bin/bash

# (1) Create the secret key
openssl genrsa -out secret.key 2048

# (2) Create a public key
#     We can create public keys from a secret key easily.
openssl rsa -pubout < secret.key > public.key

# (3) Convert the secret key to PKSC8 format that Java can read.
openssl pkcs8 -in secret.key -out secret.key.pkcs8 -topk8 -nocrypt

Javaで暗号化復号化

https://github.com/kagyuu/RSAExam/blob/master/RSAExam/src/main/java/com/mycompany/rsaexam/RSAUtil.java

package com.mycompany.rsaexam;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import javax.crypto.Cipher;

public class RSAUtil {
    public static String encryptLicense(File license) throws Exception {
        PrivateKey priKey = KeyFactory.getInstance("RSA")
                .generatePrivate(new PKCS8EncodedKeySpec(readKey("secret.key.pkcs8")));

        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, priKey);

        byte[] rawLicense = Files.readAllBytes(license.toPath());
        byte[] encryptedLicense = cipher.doFinal(rawLicense);
        byte[] base64License = Base64.getMimeEncoder().encode(encryptedLicense);
        return new String(base64License);
    }

    public static String decryptLicense(File license) throws Exception {
        PublicKey pubKey = KeyFactory.getInstance("RSA")
                .generatePublic(new X509EncodedKeySpec(readKey("public.key")));

        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, pubKey);

        byte[] base64License = Files.readAllBytes(license.toPath());
        byte[] encryptedLicense = Base64.getMimeDecoder().decode(base64License);
        byte[] rawLicense = cipher.doFinal(encryptedLicense);
        return new String(rawLicense);
    }
    
    private static byte[] readKey(final String fileName) throws Exception {

        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        InputStream keyStream = loader.getResourceAsStream(fileName);
        try (
                BufferedReader br = new BufferedReader(new InputStreamReader(keyStream))) {
            String line;
            StringBuilder sb = new StringBuilder();
            boolean isContents = false;

            while ((line = br.readLine()) != null) {
                if (line.matches("[-]+BEGIN[ A-Z]+[-]+")) {
                    isContents = true;
                } else if (line.matches("[-]+END[ A-Z]+[-]+")) {
                    break;
                } else if (isContents) {
                    sb.append(line);
                }
            }

            return Base64.getDecoder().decode(sb.toString());
        } catch (FileNotFoundException e) {
            throw new Exception("File not found.", e);
        } catch (IOException e) {
            throw new Exception("can't read the PEM file.", e);
        }
    }    
}

使用例

https://github.com/kagyuu/RSAExam/blob/master/RSAExam/src/test/java/com/mycompany/rsaexam/test/RSAUtilTest.java

package com.mycompany.rsaexam.test;

import com.mycompany.rsaexam.RSAUtil;
import java.io.File;
import java.io.FileOutputStream;
import org.junit.Test;

public class RSAUtilTest {

    public RSAUtilTest() {
    }

    @Test
    public void hello() throws Exception {
        String encrypted = RSAUtil.encryptLicense(new File("src/test/resources/License.txt"));
        System.out.println("***** ENCREPTYED *****");
        System.out.println(encrypted);
        
        File tmpFile = File.createTempFile("tmp", ".txt");
        tmpFile.deleteOnExit();
        try (FileOutputStream fout = new FileOutputStream(tmpFile)) {
            fout.write(encrypted.getBytes());
        }
        
        String decripted = RSAUtil.decryptLicense(tmpFile);
        System.out.println("***** DECRYPTED *****");
        System.out.println(decripted);
    }
}

ところで、



Java#JavaSE


トップ   編集 凍結 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS   sitemap
Last-modified: 2015-03-24 (火) 01:22:05 (620d)
ISBN10
ISBN13
9784061426061