繁体   English   中英

Java 7中的加密

[英]Encryption in Java 7

在Java 7中,我想使用SHA-256和AES-256进行密码的加密和解密 我尝试使用PBKDF2WithHmacSHA256 ,但是Java7不支持此功能。 你有什么想法? 请告诉我图书馆信息。

谢谢。

例子(Java8)

public class PasswordUtil {

    private static final String ALGORITHM = "PBKDF2WithHmacSHA256";
    private static final int ITERATION_COUNT = 10000;
    private static final int KEY_LENGTH = 256;

    /**
     *
     * @param password
     * @param salt
     * @return
     */
    public static String getSafetyPassword(String password, String salt) {

        char[] passCharAry = password.toCharArray();
        byte[] hashedSalt = getHashedSalt(salt);

        PBEKeySpec keySpec = new PBEKeySpec(passCharAry, hashedSalt, ITERATION_COUNT, KEY_LENGTH);

        SecretKeyFactory skf;
        try {
            skf = SecretKeyFactory.getInstance(ALGORITHM);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }

        SecretKey secretKey;
        try {
            secretKey = skf.generateSecret(keySpec);
        } catch (InvalidKeySpecException e) {
            throw new RuntimeException(e);
        }
        byte[] passByteAry = secretKey.getEncoded();

        StringBuilder sb = new StringBuilder(64);
        for (byte b : passByteAry) {
            sb.append(String.format("%02x", b & 0xff));
        }
        return sb.toString();
    }

    /**
     *
     * @param salt
     * @return
     */
    private static byte[] getHashedSalt(String salt) {
        MessageDigest messageDigest;
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        messageDigest.update(salt.getBytes());
        return messageDigest.digest();
    }
}

在JAVA 7中使用AES对密码进行加密解密

Encryptionsss.java ::

public class Encryptionsss {

public static void main(String[] args) throws Exception {

     try {
         String text = "Hello World";
         String key = "1234567891234567";
         // Create key and cipher
         Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
         Cipher cipher = Cipher.getInstance("AES");

     // encrypt the text
     cipher.init(Cipher.ENCRYPT_MODE, aesKey);
     byte[] encrypted = cipher.doFinal(text.getBytes());
     System.out.println("Encrypted text: " + new String(encrypted));

     // decrypt the text
     cipher.init(Cipher.DECRYPT_MODE, aesKey);
     String decrypted = new String(cipher.doFinal(encrypted));
     System.out.println("Decrypted text: " + decrypted);
  }catch(Exception e) {
     e.printStackTrace();
  }

    String plainText = "Hello World";

    /**
     * Generate new Key 
     */
//  String str = generatenewkeyasString();



 /*** Generate Cipher Text from Key(We are using same key stored in String-str)
 ****/


    String str = "]˜??4I-S@æ,Ôt";
    byte[] data = str.getBytes();
    SecretKey key2 = new SecretKeySpec(data, 0, data.length, "AES");
    byte[] cipherText = encryptText(plainText, key2);
    String scipherText = new String(cipherText);
   /**
    *
    * Decrypt Cipher Text with Key****/

    cipherText = scipherText.getBytes();
    String decryptedText = decryptText(cipherText, key2);
    System.out.println("ScipherText:" + scipherText);
    System.out.println("Original Text:" + plainText);
    System.out.println("AES Key (Hex Form):"
            + bytesToHex(key2.getEncoded()));
    System.out.println("Encrypted Text (Hex Form):"
            + bytesToHex(cipherText));
    System.out.println("Descrypted Text:" + decryptedText);

}

/**
 * 
 * @return byte[] as String
 * @Generate Key
 */

private static String generatenewkeyasString() throws Exception {
    SecretKey secKey = KeyGenerator.getInstance("AES").generateKey();
    byte[] data = secKey.getEncoded();
    String str = new String(data);
    return str;

}

/**
 * 
 * Encrypts plainText in AES using the secret key
 * 
 * @param plainText
 * 
 * @param secKey
 * 
 * @return
 * 
 * @throws Exception
 */

public static byte[] encryptText(String plainText, SecretKey secKey)
        throws Exception {

    // AES defaults to AES/ECB/PKCS5Padding in Java 7

    Cipher aesCipher = Cipher.getInstance("AES");
    aesCipher.init(Cipher.ENCRYPT_MODE, secKey);
    byte[] byteCipherText = aesCipher.doFinal(plainText.getBytes());
    return byteCipherText;

}

/**
 * 
 * Decrypts encrypted byte array using the key used for encryption.
 * 
 * @param byteCipherText
 * @param secKey
 * 
 * @return
 * 
 * @throws Exception
 */

public static String decryptText(byte[] byteCipherText, SecretKey secKey)
        throws Exception {

    // AES defaults to AES/ECB/PKCS5Padding in Java 7

    Cipher aesCipher = Cipher.getInstance("AES");
    aesCipher.init(Cipher.DECRYPT_MODE, secKey);
    byte[] bytePlainText = aesCipher.doFinal(byteCipherText);
    return new String(bytePlainText);

}

/**
 * 
 * Convert a binary byte array into readable hex form
 * 
 * @param hash
 * 
 * @return
 */

private static String bytesToHex(byte[] hash) {
    return DatatypeConverter.printHexBinary(hash);

}

}

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM