Created
April 7, 2019 20:07
-
-
Save rodionbykov/675850e633a47149193f0b1c26250984 to your computer and use it in GitHub Desktop.
Using Asymmetric Keys for signature in Coldfusion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.rodionbykov; | |
import java.io.File; | |
import java.io.FileReader; | |
import java.io.IOException; | |
import java.security.KeyPair; | |
import java.security.Security; | |
import java.security.Signature; | |
import java.util.Arrays; | |
import org.bouncycastle.jce.provider.BouncyCastleProvider; | |
import org.bouncycastle.openssl.PEMReader; | |
import org.bouncycastle.openssl.PasswordFinder; | |
import biz.source_code.base64Coder.Base64Coder; | |
public class ColdSignature { | |
public static String signMessage (String message, String pemFile, String pwd, String sigtype) throws Exception { | |
Security.addProvider(new BouncyCastleProvider()); | |
File privateKey = new File(pemFile); | |
KeyPair keyPair = readKeyPair(privateKey, pwd.toCharArray()); | |
Signature signature = Signature.getInstance(sigtype); | |
signature.initSign(keyPair.getPrivate()); | |
signature.update(message.getBytes()); | |
byte [] signatureBytes = signature.sign(); | |
return new String(Base64Coder.encode(signatureBytes)); | |
} | |
private static KeyPair readKeyPair (File privateKey, char [] keyPassword) throws IOException { | |
FileReader fileReader = new FileReader(privateKey); | |
PEMReader r = new PEMReader(fileReader, new DefaultPasswordFinder(keyPassword)); | |
try { | |
return (KeyPair) r.readObject(); | |
} catch (IOException ex) { | |
throw new IOException("The private key could not be decrypted", ex); | |
} finally { | |
r.close(); | |
fileReader.close(); | |
} | |
} | |
private static class DefaultPasswordFinder implements PasswordFinder { | |
private final char [] password; | |
private DefaultPasswordFinder(char [] password) { | |
this.password = password; | |
} | |
@Override public char[] getPassword() { | |
return Arrays.copyOf(password, password.length); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment