Key 在java中将字符串转换为密钥以进行RC4加密

Key 在java中将字符串转换为密钥以进行RC4加密,key,encryption,java,Key,Encryption,Java,如何将java字符串转换为密钥,以便用于以下RC4加密算法?我有一个密码,需要用作加密密钥 private static String rc4(String plaintext, int mode, Key key) throws Exception { Cipher cipher = Cipher.getInstance("RC4"); cipher.init(mode, (java.security.Key) key); return new String(ciphe

如何将java字符串转换为密钥,以便用于以下RC4加密算法?我有一个密码,需要用作加密密钥

private static String rc4(String plaintext, int mode, Key key) throws Exception {
    Cipher cipher = Cipher.getInstance("RC4");
    cipher.init(mode, (java.security.Key) key);
    return new String(cipher.doFinal(plaintext.getBytes()));
}

public static String encrypt(String plaintext, Key key) throws Exception {
    return rc4(plaintext, Cipher.ENCRYPT_MODE, key);
}

为了将表示密码的字符串(即,人类可以记忆的短字符串)转换为RC4或其他密码的密钥,安全性方面很重要的一点是使用指定的参数化字符串,以使其速度适当缓慢。作为此KDF的输入包含的内容也很有用(对于文件或会话加密,在每次使用时发送一个16字节的随机salt是可以的。如果额外的数据是一个问题,salt可以通过密码所有者的ID、服务器名称和一个恒定的服务器唯一值串联而成。在salt中添加一些随机和秘密的内容会有所帮助;有些人称之为pepper)

不使用密码的截断散列或任何其他快速且未加密的方法的原因是,即使使用标准PC,密码系统也会非常容易受到暴力攻击。密码破解和其他暴力密钥恢复似乎是一个真正的行业,CPU和GPU使用了无数千瓦的电力,可能还有一个kFPGA机架的ey(双关语)市场

一个值得推荐但不幸不是那么标准的KDF是;这将是我的第二选择;如果我急于在Java平台上将其投入生产,我可能会使用它,假设
SecretKeyFactory.getInstance(“PBKDF2WithHmacSHA256”)
可用。请注意,在未仔细查看查询返回的某些代码的情况下,不要使用这些代码,尤其是当它使用的迭代计数为1000时(很遗憾,这是常见的,在中提到的唯一值,并且在面对有能力的攻击者时,这是完全不够的)。此外,请根据密码允许的任何情况调整密钥大小参数(对于RC4,应该是256字节)


正如中正确指出的,输入的字符集是一个需要仔细处理的问题。

谁将解密此消息

如果你同时写加密和解密,fgrieu有一些很好的建议

另一方面,如果希望与其他RC4加密实现互操作,则必须以与另一端实现兼容的方式将字符串转换为密钥

为了与实施相兼容, “在CipherSaber中,RC4密钥数组由用户的CipherSaber密钥和10字节的初始化向量(IV)组成。”——

反过来,CipherSaber密钥通常是6或7个单词长的密码短语。 (我看到的Java实现通常在从IV和ASCII文本密码字符串生成RC4密钥字节[]数组的过程中使用passphrase.getBytes()或passphrase.charAt()。 解密的Java实现只需从加密消息的开头读取IV。 加密的Java实现通常使用来生成IV。 )

其他使用RC4的实现方式有所不同——我无法猜测您要与哪个实现进行互操作。 希望该实现有足够的文档记录,以便您了解需要了解的内容。

import java.io.IOException;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;

import org.apache.commons.codec.DecoderException;
import org.bouncycastle.util.encoders.Hex;

public class RC4Algo {

    public static void main(String args[])throws IOException, NoSuchAlgorithmException, DecoderException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException
    {
        decryptRC4();
    }

    static String decryptRC4() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException{

        byte[] plainBytes = "testString".getBytes();

        String hashedKey = hashedData("thisismysecretkey");

        //Generate a new key using KeyGenerator
        /*KeyGenerator rc4KeyGenerator = KeyGenerator.getInstance("RC4");
        SecretKey key = rc4KeyGenerator.generateKey();*/

        Key key = new SecretKeySpec(Hex.decode(hashedKey), "RC4"); //String to key conversion using Hex.decode to convert to byte []

        // Create Cipher instance and initialize it to encrytion mode
        Cipher cipher = Cipher.getInstance("RC4");  // Transformation of the algorithm
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] cipherBytes = cipher.doFinal(plainBytes);

        String encoded = encodeBase64(cipherBytes);

        String decoded = decodeBase64(encoded);

        // Reinitialize the Cipher to decryption mode
        cipher.init(Cipher.DECRYPT_MODE,key, cipher.getParameters());
        byte[] plainBytesDecrypted = cipher.doFinal(Hex.decode(decoded));

        System.out.println("Decrypted Data : "+new String(plainBytesDecrypted));
        return new String(plainBytesDecrypted);
    }

    static String decodeBase64(String encodedData){
        byte[] b = Base64.getDecoder().decode(encodedData);
        String decodedData = DatatypeConverter.printHexBinary(b);
        return decodedData;
    }

    static String encodeBase64(byte[] data){
        byte[] b = Base64.getEncoder().encode(data);
        String encodedData = new String(b);
        /*String encodedData = DatatypeConverter.printHexBinary(b);*/
        return encodedData;
    }

    static String hashedData(String key) throws NoSuchAlgorithmException{
        String password = key;

        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(password.getBytes());

        byte byteData[] = md.digest();

        //convert the byte to hex format method 1
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < byteData.length; i++) {
         sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
        }

        //convert the byte to hex format method 2
        StringBuffer hexString = new StringBuffer();
        for (int i=0;i<byteData.length;i++) {
            String hex=Integer.toHexString(0xff & byteData[i]);
            if(hex.length()==1) hexString.append('0');
            hexString.append(hex);
        }
        return hexString.toString();
    }

    }
导入java.security.invalidalgorithParameterException; 导入java.security.InvalidKeyException; 导入java.security.Key; 导入java.security.MessageDigest; 导入java.security.NoSuchAlgorithmException; 导入java.util.Base64; 导入javax.crypto.BadPaddingException; 导入javax.crypto.Cipher; 导入javax.crypto.IllegalBlockSizeException; 导入javax.crypto.NoSuchPaddingException; 导入javax.crypto.spec.SecretKeySpec; 导入javax.xml.bind.DatatypeConverter; 导入org.apache.commons.codec.DecoderException; 导入org.bouncycastle.util.encoders.Hex; 公共类RC4Algo{ 公共静态void main(字符串args[])抛出IOException、NoSuchAlgorithmException、DecodeException、InvalidKeyException、NoSuchPaddingException、IllegalBlockSizeException、BadPaddingException、InvalidAlgorithmParameterException { 解密RC4(); } 静态字符串decryptRC4()抛出NoSuchAlgorithmException、NoSuchPaddingException、InvalidKeyException、IllegalBlockSizeException、BadPaddingException、InvalidGorthmParameterException{ byte[]plainBytes=“testString”.getBytes(); 字符串hashedKey=hashedData(“thisismysecretkey”); //使用KeyGenerator生成新密钥 /*KeyGenerator rc4KeyGenerator=KeyGenerator.getInstance(“RC4”); SecretKey key=rc4KeyGenerator.generateKey()*/ Key Key=new SecretKeySpec(Hex.decode(hashedKey),“RC4”);//使用Hex.decode转换为字节[]的字符串到键的转换 //创建密码实例并将其初始化为加密模式 Cipher Cipher=Cipher.getInstance(“RC4”);//算法的转换 cipher.init(cipher.ENCRYPT_模式,密钥); 字节[]cipherBytes=cipher.doFinal(纯字节); 字符串编码=encodeBase64(cipherBytes); 已解码字符串=decodeBase64(已编码); //将密码重新初始化为解密模式 init(cipher.DECRYPT_模式,key,cipher.getParameters()); 字节[]明文解密=cipher.doFinal(十六进制解码(解码)); System.out.println(“解密数据:+新字符串(明文解密)); 返回新字符串(明文已解密); } 静态字符串decodeBase64(字符串编码数据){ 字节[]b=Base64.getDecoder().decode(encodedData); 字符串decodedData=DatatypeConverter.printHexBinary(b); 返回解码数据; } 静态字符串encodeBase64(字节[]数据){ 字节[]b=Base64.getEncoder().encode(数据); 字符串编码数据=新字符串(b); /*字符串encodedData=DatatypeConverter.printHexBinary(b)*/ 返回编码数据; } 静态字符串hashedData(字符串键)抛出NoSuchAlgo