Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
 package com.google.code.springcryptoutils.core.cipher.asymmetric;
 
 
 import java.util.Map;

The default implementation for performing asymmetric encryption/decryption with base64 encoded strings and keys which are mapped with a logical name.

Author(s):
Mirko Caserta (mirko.caserta@gmail.com)
    private String algorithm = "RSA";
    private String charsetName = "UTF-8";
    private Mode mode;
    private Map<StringKeykeyMap;

    
The asymmetric key algorithm. The default is RSA.

Parameters:
algorithm the asymmetric key algorithm
    public void setAlgorithm(String algorithm) {
        this. = algorithm;
    }

    
The charset used when a message must be converted into a raw byte array. Default is UTF-8.

Parameters:
charsetName the charset name
    public void setCharsetName(String charsetName) {
        this. = charsetName;
    }

    
Sets the encryption/decryption mode.

Parameters:
mode the encryption/decryption mode
    public void setMode(Mode mode) {
        this. = mode;
    }

    
Sets the map of keys. The map key is a string representing the logical name of the key (the keyId).

Parameters:
keyMap the key map
    public void setKeyMap(Map<StringKeykeyMap) {
        this. = keyMap;
    }

    
Encrypts/decrypts a message based on the underlying mode of operation.

Parameters:
keyId the key id
message if in encryption mode, the clear-text message, otherwise the base64 encoded message to decrypt
Returns:
if in encryption mode, the base64 encoded encrypted message, otherwise the decrypted message
Throws:
AsymmetricEncryptionException on runtime errors
See also:
setMode(com.google.code.springcryptoutils.core.cipher.Mode)
    public String encrypt(String keyIdString message) {
        final Key key = .get(keyId);
        if (key == null) {
            throw new AsymmetricEncryptionException("key not found: keyId=" + keyId);
        }
        try {
            final Cipher cipher = Cipher.getInstance();
            switch () {
                case :
                    final byte[] messageAsByteArray = message.getBytes();
                    cipher.init(.key);
                    return Base64.encodeBase64String(cipher.doFinal(messageAsByteArray));
                case :
                    final byte[] encryptedMessage = Base64.decodeBase64(message);
                    cipher.init(.key);
                    return new String(cipher.doFinal(encryptedMessage), );
                default:
                    return null;
            }
        } catch (Exception e) {
            throw new AsymmetricEncryptionException("error encrypting/decrypting message; mode=" + e);
        }
    }
New to GrepCode? Check out our FAQ X