Java using AES 256 and 128 Symmetric-key encryption

前端 未结 5 1566
余生分开走
余生分开走 2020-12-07 19:29

I am new in cipher technology. I found this code to do Symmetric Encryption.

byte[] key = //... secret sequence of bytes
byte[] dataToSend = ...
Cipher c = C         


        
5条回答
  •  没有蜡笔的小新
    2020-12-07 19:53

    The Answer for 128 bit

    The following method is to encrypt a string (valueEnc) with AES encryption:

    private static final String ALGORITHM = "AES"; 
    
    public String encrypt(final String valueEnc, final String secKey) { 
    
        String encryptedVal = null;
    
        try {
            final Key key = generateKeyFromString(secKey);
            final Cipher c = Cipher.getInstance(ALGORITHM);
            c.init(Cipher.ENCRYPT_MODE, key);
            final byte[] encValue = c.doFinal(valueEnc.getBytes());
            encryptedVal = new BASE64Encoder().encode(encValue);
        } catch(Exception ex) {
            System.out.println("The Exception is=" + ex);
        }
    
        return encryptedVal;
    }
    

    The next method will decrypt the AES encrypted string (encryptedVal):

        public String decrypt(final String encryptedValue, final String secretKey) {
    
        String decryptedValue = null;
    
        try {
    
            final Key key = generateKeyFromString(secretKey);
            final Cipher c = Cipher.getInstance(ALGORITHM);
            c.init(Cipher.DECRYPT_MODE, key);
            final byte[] decorVal = new BASE64Decoder().decodeBuffer(encryptedValue);
            final byte[] decValue = c.doFinal(decorVal);
            decryptedValue = new String(decValue);
        } catch(Exception ex) {
            System.out.println("The Exception is=" + ex);
        }
    
        return decryptedValue;
    }
    

    The secKey is a 128-bit key, which is encoded in the BASE64Encoder. The BASE64Decoder in the following method generates an appropriate 128-bit key

    private Key generateKeyFromString(final String secKey) throws Exception {
        final byte[] keyVal = new BASE64Decoder().decodeBuffer(secKey);
        final Key key = new SecretKeySpec(keyVal, ALGORITHM);
        return key;
    }
    

提交回复
热议问题