简体   繁体   English

如何使用JavaKeyStore将AES密钥存储在数据库中,目前我将密钥存储在扩展名为.JCEKS的文件夹中,

[英]How to store the AES Key in database using JavaKeyStore, currently i am storing the key in a folder with .JCEKS extension,

How to Store the AES Key in Database using JavaKeyStore, please check the complete code and its straight forward. 如何使用JavaKeyStore在数据库中存储AES密钥,请检查完整的代码及其简单明了。 Currently i am storing the Key in .JCEKS extension in a given location, need to store the Key in database and read it back for encryption. 当前,我将密钥存储在给定位置的.JCEKS扩展名中,需要将密钥存储在数据库中并读回以进行加密。 Please help me out. 请帮帮我。

Note: This code is working any one who wants to encrypt and decrypt and store the date in the database use my code. 注意:此代码适用于任何希望使用我的代码进行加密,解密并将日期存储在数据库中的人。 Key generated gets save in file format and is retrieved back for reuse, encrypt or decrypt. 生成的密钥以文件格式保存,并取回以重新使用,加密或解密。

package user.dao;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import java.security.KeyStore.PasswordProtection;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;

import de.blowfish.core.Blowfish;

import user.util.UserConstants;

import user.bean.UserLoginBean;
import user.util.DButil;



public class UserDao {

public int insertUserDetails(Object bean)
{

    user.bean.UserLoginBean beanobj=(UserLoginBean)bean;
    Connection conn=null;
    PreparedStatement ps=null;
    PreparedStatement ps1=null;
    ResultSet rs = null;
    int result=0;
    try{

    conn=DButil.getConnection();
    StringBuffer sbinsert=new StringBuffer();
    sbinsert.append("insert into ");
    sbinsert.append(UserConstants.USER_DETAILS_TABLE_NAME);
    sbinsert.append(" values(?,?,?,?,?,?)");

    //KeyStore Table

    conn=DButil.getConnection();
    StringBuffer sbinsert1 =new StringBuffer();
    sbinsert1.append("insert into ");
    sbinsert1.append(UserConstants.USER_DETAILS_TABLE_NAME1);
    sbinsert1.append(" values(?,?)");

    //

    Security.addProvider(new blowfishProvider());


    Cipher cipher = Cipher.getInstance("AES128_CBC", "blowfish");
    KeyGenerator keyGen = KeyGenerator.getInstance("AES", "blowfish");
    SecretKey secKey = keyGen.generateKey();



    // Storing the secret Key
                final String keyStoreFile = "C:\\mykey.jceks";
                 //String keyStoreFile = new String(sbinsert1);
                //final String keyStoreDB = beanobj.getKeylock();
                 KeyStore keyStore = createKeyStore(keyStoreFile, "java0123");
                 System.out.println("Stored Key: " + (secKey));
                 System.out.println("secured key: " + (keyStore));


    // store the secret key
                 KeyStore.SecretKeyEntry keyStoreEntry = new KeyStore.SecretKeyEntry(secKey);
                 PasswordProtection keyPassword = new PasswordProtection("www-secret".toCharArray());
                 keyStore.setEntry("mySecretKey", keyStoreEntry, keyPassword);
                 keyStore.store(new FileOutputStream(keyStoreFile), "java0123".toCharArray());
                 //keyStore.store(new FileOutputStream(keyStoreDB), "java0123".toCharArray());


    //Encryption of string
    String clearText = beanobj.getPassword() ;
    byte[] clearTextBytes = clearText.getBytes("UTF8");
    cipher.init(Cipher.ENCRYPT_MODE, secKey);
    byte[] cipherBytes = cipher.doFinal(clearTextBytes);
    String cipherText = new String(cipherBytes, "UTF8");

    //Decryption of String
    cipher.init(Cipher.DECRYPT_MODE, secKey );
    byte[] decryptedBytes = cipher.doFinal(cipherBytes);
    String decryptedText = new String(decryptedBytes, "UTF8");

    System.out.println("Before encryption: " + clearText);
    System.out.println("After encryption: " + cipherText);
    System.out.println("After decryption: " + decryptedText);

    //


    ps=conn.prepareStatement(sbinsert.toString());
    ps.setString(1,beanobj.getFirstname());
    ps.setString(2, beanobj.getLastname());
    ps.setString(3, beanobj.getUsername());
    ps.setString(4, cipherText);
    ps.setString(5, beanobj.getEmail());
    ps.setString(6, beanobj.getMobileno());

    ps1=conn.prepareStatement(sbinsert1.toString());
    beanobj.setKeylock("mykey"); // Dummy key for checking if logic works
    ps1.setString(1,beanobj.getUsername());
    ps1.setString(2,beanobj.getKeylock());

    result=ps.executeUpdate();
    result=ps1.executeUpdate();

    }
    catch(SQLException e)
    {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchProviderException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();


    } catch (NoSuchPaddingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (BadPaddingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    finally{
        DButil.closeAllDBResources(conn, ps, null);
    }
    return result;


    }
public boolean isRegisteredUser(String un,String pw)
{
    boolean result=false;
    Connection conn=null;
    PreparedStatement ps=null;
    ResultSet rs=null;
    try
    {
        conn=DButil.getConnection();
        StringBuffer sbselect=new StringBuffer();
        sbselect.append("select * from ");
        sbselect.append(UserConstants.USER_DETAILS_TABLE_NAME);
        sbselect.append(" where BINARY Username=? and Password=?");
        ps=conn.prepareStatement(sbselect.toString());


        // Retreving the key 

        Security.addProvider(new FlexiCoreProvider());
        Cipher cipher1 = Cipher.getInstance("AES128_CBC", "FlexiCore");
        KeyStore keyStore = KeyStore.getInstance("JCEKS");
        System.out.println(keyStore);
        FileInputStream fis = new FileInputStream("C:\\mykey.jceks";);

        keyStore.load(fis, "java0123".toCharArray());              
        Key secKey = keyStore.getKey("mySecret","www-secret".toCharArray());


        //Encrypting the User Passowrd and comparing with the DB enPassword one way process

        String clearText = pw ;
        byte[] clearTextBytes = clearText.getBytes("UTF8");
        cipher1.init(Cipher.ENCRYPT_MODE, secKey);
        byte[] cipherBytes = cipher1.doFinal(clearTextBytes);
        String cipherText1 = new String(cipherBytes, "UTF8");




        ps.setString(1, un);
        ps.setString(2, cipherText1);
        //System.out.println(ps.toString());
        rs=ps.executeQuery();
        if(rs.next())
        {
            result=true;
        }
    }
    catch(SQLException e)
    {
        System.out.println(e);
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchProviderException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (CertificateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (BadPaddingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    finally
    {
        DButil.closeAllDBResources(conn, ps, rs);
    }


    return result;
}
public int executeUpdate(String query)
{
    int result=0;
    Connection conn=null;
    PreparedStatement ps=null;
    try
    {
        conn=DButil.getConnection();
        ps=conn.prepareStatement(query);
        result=ps.executeUpdate();

    }
    catch(SQLException e)
    {
        e.printStackTrace();

    }
    finally{
        DButil.closeAllDBResources(conn, ps, null);
    }
    return result;
}

private static java.security.KeyStore createKeyStore(String keyStoreFile,
        String pw) throws Exception {
    // TODO Auto-generated method stub
     File file = new File("mykey.jceks");
     /**
      * Note that if you are storing a SecretKey or using any part of the SunJCE provider
      *  (Java Cryptography Extension),
      *  you will need to set your KeyStore type to JCEKS.
      */
        final KeyStore keyStore = KeyStore.getInstance("JCEKS");
        if (file.exists()) {
            // .keystore file already exists => load it
            keyStore.load(new FileInputStream(file), www.toCharArray());
        } else {
            // .keystore file not created yet => create it
            keyStore.load(null, null);
            keyStore.store(new FileOutputStream("mykey1.jceks"), www.toCharArray());
        }

        return keyStore;
       }

       }

Change keyStore.store(new FileOutputStream(keyStoreFile), "java0123".toCharArray()); 更改keyStore.store(new FileOutputStream(keyStoreFile), "java0123".toCharArray()); and replace the FileOutputStream with a ByteArrayOutputStream . 并将FileOutputStream替换为ByteArrayOutputStream Use ByteArrayOutputStream.toByteArray() to retrieve the resulting blob. 使用ByteArrayOutputStream.toByteArray()检索生成的Blob。 Then either store the (variable sized) blob in the byte array directly into your DB. 然后将字节数组中的(可变大小)blob直接存储到您的数据库中。

You may use CipherOutputStream connected to the ByteArrayOutputStream to additionally encrypt the KeyStore instance. 您可以使用连接到ByteArrayOutputStream CipherOutputStream额外加密KeyStore实例。 If you do this then don't forget to close the CipherOutputStream or your data may become corrupted. 如果这样做,则别忘了关闭CipherOutputStream否则您的数据可能会损坏。

If you require characters for some reason or other, first base64 encode the blob and store the result. 如果出于某种原因需要字符,则首先使用base64对blob进行编码并存储结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用java中的密钥库存储AES密钥 - Storing AES Secret key using keystore in java 如何通过使用AES算法在android中存储用于加密文件的密钥 - How to store the key used to encrypt files in android by using AES algorithm 我用AES密钥加密了AES密钥,当我尝试解密密钥时,将密钥作为字符串存储在数据库中: - I have encrypted AES Key with AES Key,Stored the Key as String in DataBase, when i try to decrypt the Key i get : 我在解密使用 RSA 生成的公钥(.jks)编码的 128 位 AES 密钥时收到 BadPaddingException - I am getting BadPaddingException while decrypting an 128 bit AES key which has been encoded by using RSA generated public key(.jks) 如何在Python中指定AES密钥? - How can I specify an AES key in Python? 安全地在Android设备中存储AES密钥 - Storing AES Key in Android Device Securely 如何使用AES加密创建Java密钥存储(.jks)文件 - How to create Java Key Store (.jks) file with AES encryption 使用Oracle Java 8 JRE打开JCEKS密钥库时出现“java.io.IOException:无效的密钥格式”172 - “java.io.IOException: Invalid secret key format” when opening JCEKS key store with Oracle Java 8 JRE 172 我正在尝试在 aes 算法中打印密钥。 但打印的密钥大小不是 128 位 - i am trying to print the secret key in aes algo. but the key size printed is not 128 bits EC 密钥对生成 Java 代码与 JavaKeyStore Explorer 应用程序 - EC Key Pair Generation Java code vs JavaKeyStore Explorer Application
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM