crypto
List available Encryption/Decryption algorithms
This is an example of how to list all the available Encryption/Decryption algorithms. In order to do so we have created a method, Set<String> getAlgorithms(String serviceType)
. The method gets a String parameter that is the serviceType
for which it will return the algorithms. The steps of the method are the ones below:
- Create a new Set of String elements, to hold the algorithms.
- Use
getProviders()
API method of Security to get an array of the Providers. - For every Provider get a view of the property keys contained in this provider, using
keySet()
API method of Provider. - Iterate over the keys. For every key check if it starts with the specified String
serviceType
or if it starts with the"Alg.Alias."
String followed by the StringserviceType
. If so, add the rest of the key to the Set of the algorithms.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core; import java.security.Provider; import java.security.Security; import java.util.Iterator; import java.util.Set; import java.util.TreeSet; public class ListAvailableEncryptionDecryptionAlgorithms { public static void main(String[] args) { // get an array containing all the installed providers Provider[] providers = Security.getProviders(); for (int i=0; i<providers.length; i++) { // get a view of the property keys contained in this provider Set<Object> keys = providers[i].keySet(); for (Iterator<Object> it=keys.iterator(); it.hasNext();) { String key = it.next().toString(); key = key.split(" ")[0]; if (key.startsWith("Alg.Alias.")) { // strip the alias key = key.substring(10); } int index = key.indexOf('.'); String serviceType = key.substring(0, index); Set<String> algorithms = getAlgorithms(serviceType); System.out.println(serviceType); for (Iterator<String> iter=algorithms.iterator(); iter.hasNext();) { System.out.println("t" + iter.next()); } } } } private static Set<String> getAlgorithms(String serviceType) { Set<String> algorithms = new TreeSet<String>(); // get an array containing all the installed providers Provider[] providers = Security.getProviders(); for (int i=0; i<providers.length; i++) { // get a view of the property keys contained in this provider Set<Object> keys = providers[i].keySet(); for (Iterator<Object> it=keys.iterator(); it.hasNext();) { String key = it.next().toString(); key = key.split(" ")[0]; if (key.startsWith(serviceType+".")) { algorithms.add(key.substring(serviceType.length()+1)); } else if (key.startsWith("Alg.Alias."+serviceType+".")) { algorithms.add(key.substring(serviceType.length()+11)); } } } return algorithms; } }
This was an example of how to list all the available Encryption/Decryption algorithms in Java.