I've searched forums and answers but I can't figure out my problem, I am trying to verify a signature , but it always returns false, am I doing something wrong? I generate the key, sign it and then verify it (the byte arrays are not null)
public void Keygen() throws java.rmi.RemoteException, NoSuchAlgorithmException, IOException, SignatureException, NoSuchProviderException, InvalidKeyException {
KeyPairGenerator Keygen = KeyPairGenerator.getInstance("DSA");
Keygen.initialize(1024, random);
KeyPair pair = Keygen.generateKeyPair();
priv = pair.getPrivate();
pub = pair.getPublic();
}
public byte [] sign (int k)throws java.rmi.RemoteException, NoSuchAlgorithmException, SignatureException, InvalidKeyException , NoSuchProviderException
Signature dsa = Signature.getInstance("SHA1withDSA", "SUN");
dsa.initSign(priv);
String data = "aa";
byte[] b = data.getBytes();
dsa.update(b);
realSig = dsa.sign();
key = pub.getEncoded();
return realSig;
}
public int Versig(byte [] sigkeys) throws java.rmi.RemoteException, NoSuchAlgorithmException, IOException, SignatureException, NoSuchProviderException, InvalidKeyException, InvalidKeySpecException{
byte [] pkb = getenckey();
KeyFactory kf = KeyFactory.getInstance("DSA");
PublicKey pubKey = kf.generatePublic(new X509EncodedKeySpec(pkb));
/* create a Signature object and initialize it with the public key */
Signature sig = Signature.getInstance("SHA1withDSA", "SUN");
sig.initVerify(pubKey);
String data2 = "bb";
byte[] c = data2.getBytes();
sig.update(c);
boolean verifies = sig.verify(sigkeys);
System.out.println("1 " + verifies);
if (verifies == true) {
System.out.println(" 2 " + verifies);
return (1);
} else {
return (2);
}
You are signing String data = "aa"; in sign method while verifying String data2 = "bb"; so the signature verification will return false.
digitally signing the data to check it's integrity (which means no alter to the data).
I hope this could help!
Related
Im trying to write a program to encrypt any type of file. I had my encryption classes already done, when I noticed (at first it worked) that I am getting an AEADBadTagException whenever I try to decrypt any of my files.
Here is my encryption/decryption class:
class Encryptor {
private static final String algorithm = "AES/GCM/NoPadding";
private final int tagLengthBit = 128; // must be one of {128, 120, 112, 104, 96}
private final int ivLengthByte = 12;
private final int saltLengthByte = 64;
protected final Charset UTF_8 = StandardCharsets.UTF_8;
private CryptoUtils crypto = new CryptoUtils();
// return a base64 encoded AES encrypted text
/**
*
* #param pText to encrypt
* #param password password for encryption
* #return encoded pText
* #throws Exception
*/
protected byte[] encrypt(byte[] pText, char[] password) throws Exception {
// 64 bytes salt
byte[] salt = crypto.getRandomNonce(saltLengthByte);
// GCM recommended 12 bytes iv?
byte[] iv = crypto.getRandomNonce(ivLengthByte);
// secret key from password
SecretKey aesKeyFromPassword = crypto.getAESKeyFromPassword(password, salt);
Cipher cipher = Cipher.getInstance(algorithm);
// ASE-GCM needs GCMParameterSpec
cipher.init(Cipher.ENCRYPT_MODE, aesKeyFromPassword, new GCMParameterSpec(tagLengthBit, iv));
byte[] cipherText = cipher.doFinal(pText);
// prefix IV and Salt to cipher text
byte[] cipherTextWithIvSalt = ByteBuffer.allocate(iv.length + salt.length + cipherText.length).put(iv).put(salt)
.put(cipherText).array();
Main.clearArray(password, null);
Main.clearArray(null, salt);
Main.clearArray(null, iv);
Main.clearArray(null, cipherText);
aesKeyFromPassword = null;
cipher = null;
try {
return cipherTextWithIvSalt;
} finally {
Main.clearArray(null, cipherTextWithIvSalt);
}
}
// für Files
protected byte[] decrypt(byte[] encryptedText, char[] password)
throws InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeySpecException, IllegalBlockSizeException, BadPaddingException {
// get back the iv and salt from the cipher text
ByteBuffer bb = ByteBuffer.wrap(encryptedText);
byte[] iv = new byte[ivLengthByte];
bb.get(iv);
byte[] salt = new byte[saltLengthByte];
bb.get(salt);
byte[] cipherText = new byte[bb.remaining()];
bb.get(cipherText);
// get back the aes key from the same password and salt
SecretKey aesKeyFromPassword;
aesKeyFromPassword = crypto.getAESKeyFromPassword(password, salt);
Cipher cipher;
cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.DECRYPT_MODE, aesKeyFromPassword, new GCMParameterSpec(tagLengthBit, iv));
byte[] plainText = cipher.doFinal(cipherText);
Main.clearArray(password, null);
Main.clearArray(null, iv);
Main.clearArray(null, salt);
Main.clearArray(null, cipherText);
aesKeyFromPassword = null;
cipher = null;
bb = null;
try {
return plainText;
} finally {
Main.clearArray(null, plainText);
}
}
protected void encryptFile(String file, char[] pw) throws Exception {
Path pathToFile = Paths.get(file);
byte[] fileCont = Files.readAllBytes(pathToFile);
byte[] encrypted = encrypt(fileCont, pw);
Files.write(pathToFile, encrypted);
Main.clearArray(pw, null);
Main.clearArray(null, fileCont);
Main.clearArray(null, encrypted);
}
protected void decryptFile(String file, char[] pw)
throws IOException, InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeySpecException, IllegalBlockSizeException, BadPaddingException {
Path pathToFile = Paths.get(file);
byte[] fileCont = Files.readAllBytes(pathToFile);
byte[] decrypted = decrypt(fileCont, pw);
Files.write(pathToFile, decrypted);
Main.clearArray(pw, null);
Main.clearArray(null, fileCont);
Main.clearArray(null, decrypted);
}
}
The corresponding CryptoUtils class:
class CryptoUtils {
protected byte[] getRandomNonce(int numBytes) {
byte[] nonce = new byte[numBytes];
new SecureRandom().nextBytes(nonce);
try {
return nonce;
} finally {
Main.clearArray(null, nonce);
}
}
// Password derived AES 256 bits secret key
protected SecretKey getAESKeyFromPassword(char[] password, byte[] salt)
throws NoSuchAlgorithmException, InvalidKeySpecException {
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512");
// iterationCount = 65536
// keyLength = 256
KeySpec spec = new PBEKeySpec(password, salt, 65536, 256);
SecretKey secret = new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES");
try {
return secret;
} finally {
secret = null;
}
}
// hex representation
protected String hex(byte[] bytes) {
StringBuilder result = new StringBuilder();
for (byte b : bytes) {
result.append(String.format("%02x", b));
}
try {
return result.toString();
} finally {
result.delete(0, result.length() - 1);
}
}
// print hex with block size split
protected String hexWithBlockSize(byte[] bytes, int blockSize) {
String hex = hex(bytes);
// one hex = 2 chars
blockSize = blockSize * 2;
// better idea how to print this?
List<String> result = new ArrayList<>();
int index = 0;
while (index < hex.length()) {
result.add(hex.substring(index, Math.min(index + blockSize, hex.length())));
index += blockSize;
}
try {
return result.toString();
} finally {
result.clear();
}
}
}
The Exception occurs at byte[] plainText = cipher.doFinal(cipherText); in the decrypt method.
Im unsure if the tagLenthBit must be the ivLengthByte * 8, I did try it though and it didnt make any difference.
I'm providing my own example code for AES 256 GCM file encryption with PBKDF2 key derivation because I'm too lazy to check all parts of your code :-)
The encryption is done with CipherInput-/Outputstreams because that avoids "out of memory errors" when encrypting larger files (your code is reading the complete plaintext / ciphertext in a byte array).
Please note that the code has no exception handling, no clearing of sensitive data/variables and the encryption/decryption result is a simple "file exist" routine but I'm sure you can use it as a good basis for your program.
That's a sample output:
AES 256 GCM-mode PBKDF2 with SHA512 key derivation file encryption
result encryption: true
result decryption: true
code:
import javax.crypto.*;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
public class AesGcmEncryptionInlineIvPbkdf2BufferedCipherInputStreamSoExample {
public static void main(String[] args) throws NoSuchPaddingException, NoSuchAlgorithmException, IOException,
InvalidKeyException, InvalidKeySpecException, InvalidAlgorithmParameterException {
System.out.println("AES 256 GCM-mode PBKDF2 with SHA512 key derivation file encryption");
char[] password = "123456".toCharArray();
int iterations = 65536;
String uncryptedFilename = "uncrypted.txt";
String encryptedFilename = "encrypted.enc";
String decryptedFilename = "decrypted.txt";
boolean result;
result = encryptGcmFileBufferedCipherOutputStream(uncryptedFilename, encryptedFilename, password, iterations);
System.out.println("result encryption: " + result);
result = decryptGcmFileBufferedCipherInputStream(encryptedFilename, decryptedFilename, password, iterations);
System.out.println("result decryption: " + result);
}
public static boolean encryptGcmFileBufferedCipherOutputStream(String inputFilename, String outputFilename, char[] password, int iterations) throws
IOException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, InvalidAlgorithmParameterException {
SecureRandom secureRandom = new SecureRandom();
byte[] salt = new byte[32];
secureRandom.nextBytes(salt);
byte[] nonce = new byte[12];
secureRandom.nextBytes(nonce);
Cipher cipher = Cipher.getInstance("AES/GCM/NOPadding");
try (FileInputStream in = new FileInputStream(inputFilename);
FileOutputStream out = new FileOutputStream(outputFilename);
CipherOutputStream encryptedOutputStream = new CipherOutputStream(out, cipher);) {
out.write(nonce);
out.write(salt);
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512");
KeySpec keySpec = new PBEKeySpec(password, salt, iterations, 32 * 8); // 128 - 192 - 256
byte[] key = secretKeyFactory.generateSecret(keySpec).getEncoded();
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(16 * 8, nonce);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, gcmParameterSpec);
byte[] buffer = new byte[8096];
int nread;
while ((nread = in.read(buffer)) > 0) {
encryptedOutputStream.write(buffer, 0, nread);
}
encryptedOutputStream.flush();
}
if (new File(outputFilename).exists()) {
return true;
} else {
return false;
}
}
public static boolean decryptGcmFileBufferedCipherInputStream(String inputFilename, String outputFilename, char[] password, int iterations) throws
IOException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, InvalidAlgorithmParameterException {
byte[] salt = new byte[32];
byte[] nonce = new byte[12];
Cipher cipher = Cipher.getInstance("AES/GCM/NOPadding");
try (FileInputStream in = new FileInputStream(inputFilename); // i don't care about the path as all is lokal
CipherInputStream cipherInputStream = new CipherInputStream(in, cipher);
FileOutputStream out = new FileOutputStream(outputFilename)) // i don't care about the path as all is lokal
{
byte[] buffer = new byte[8192];
in.read(nonce);
in.read(salt);
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512");
KeySpec keySpec = new PBEKeySpec(password, salt, iterations, 32 * 8); // 128 - 192 - 256
byte[] key = secretKeyFactory.generateSecret(keySpec).getEncoded();
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(16 * 8, nonce);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, gcmParameterSpec);
int nread;
while ((nread = cipherInputStream.read(buffer)) > 0) {
out.write(buffer, 0, nread);
}
out.flush();
}
if (new File(outputFilename).exists()) {
return true;
} else {
return false;
}
}
}
While performing Elliptic Curve cryptography with secp256k1 curve, I noticed that while the code and test cases compile on the Android Studio IDE they do not compile on the android device since the curve isn't defined in the jre/jdk that the mobile device uses. Changing the curve to a prime256v1 I seem to be facing difficulties in converting a hex string of the publicKey to PublicKey object.
Given the hex string of a PublicKey.getEncoded() which is in a database. I want an android client to convert the byte[] from converting the hex string into a PublicKey object. I am converting the byte[] using X509EncodedKeySpec() as follows:
public static PublicKey getPublicKey(byte[] pk) throws NoSuchAlgorithmException, InvalidKeySpecException {
EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(pk);
KeyFactory kf = KeyFactory.getInstance("EC");
PublicKey pub = kf.generatePublic(publicKeySpec);
return pub;
}
The conversion from a hex string to a byte[] happens as follows:
public static byte[] hexStringToByteArray(String hexString) {
byte[] bytes = new byte[hexString.length() / 2];
for(int i = 0; i < hexString.length(); i += 2){
String sub = hexString.substring(i, i + 2);
Integer intVal = Integer.parseInt(sub, 16);
bytes[i / 2] = intVal.byteValue();
String hex = "".format("0x%x", bytes[i / 2]);
}
return bytes;
}
The conversion from a byte[] to Hex string is as follows:
public static String convertBytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for ( int j = 0; j < bytes.length; j++ ) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars).toLowerCase();
}
However when I run this on the android app (7.0, API 24) I get the following System Error
W/System.err: java.security.spec.InvalidKeySpecException: java.lang.RuntimeException: error:0c0000b9:ASN.1 encoding routines:OPENSSL_internal:WRONG_TAG
at com.android.org.conscrypt.OpenSSLKey.getPublicKey(OpenSSLKey.java:295)
at com.android.org.conscrypt.OpenSSLECKeyFactory.engineGeneratePublic(OpenSSLECKeyFactory.java:47)
at java.security.KeyFactory.generatePublic(KeyFactory.java:357)
What is the recommended approach for converting a Hex string to a PublicKey for EC instance on an android device.
Here's sample code that you can execute:
ECDSA.java
public class ECDSA {
public static KeyPair generateKeyPair() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC");
ECGenParameterSpec ecSpec = new ECGenParameterSpec("prime256v1");
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
keyGen.initialize(ecSpec, random);
KeyPair pair = keyGen.generateKeyPair();
return pair;
}
public static PublicKey getPublicKey(byte[] pk) throws NoSuchAlgorithmException, InvalidKeySpecException {
EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(pk);
KeyFactory kf = KeyFactory.getInstance("EC");
PublicKey pub = kf.generatePublic(publicKeySpec);
return pub;
}
public static PrivateKey getPrivateKey(byte[] privk) throws NoSuchAlgorithmException, InvalidKeySpecException {
EncodedKeySpec privateKeySpec = new X509EncodedKeySpec(privk);
KeyFactory kf = KeyFactory.getInstance("EC");
PrivateKey privateKey = kf.generatePrivate(privateKeySpec);
return privateKey;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
KeyPair keyPair = ECDSA.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
// Converting byte[] to Hex
publicKeyHex = convertBytesToHex(publicKey.getEncoded());
privateKeyHex = convertBytesToHex(privateKey.getEncoded());
// Trying to convert Hex to PublicKey/PrivateKey objects
PublicKey pkReconstructed = ECDSA.getPublicKey(hexStringToByteArray(publicKeyHex));
PrivateKey skReconstructed = ECDSA.getPrivateKey(hexStringToByteArray(privateKeyHex));
// This throws an error when running on an android device
// because there seems to be some library mismatch with
// java.security.* vs conscrypt.OpenSSL.* on android.
}
Finally we get a real MCVE and we can now see that you are not using the correct class for encoded private keys. X509EncodedKeySpec is only for public keys. From the javadocs (emphasis mine):
This class represents the ASN.1 encoding of a public key, encoded
according to the ASN.1 type SubjectPublicKeyInfo.
For private keys, the correct encoding is usually a PKCS8EncodedKeySpec. The encoding can be determined by examining the output of Key.getFormat(). Therefore, change your method getPrivateKey of ECDSA to
public static PrivateKey getPrivateKey(byte[] privk) throws NoSuchAlgorithmException, InvalidKeySpecException {
EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privk);
KeyFactory kf = KeyFactory.getInstance("EC");
PrivateKey privateKey = kf.generatePrivate(privateKeySpec);
return privateKey;
}
I am trying to learn some Go and blockchains.. Starting with ECDSA signatures. Trying to figure out how to test if I had a correctly working Go implementation of ECDSA signatures, I figured I would try to create a similar version in Java and compare the results to see if I can get them to match.
So Java attempt:
public static void main(String[] args) throws Exception {
//the keys below are previously generated with "generateKey();" and base64 encoded
generateKey();
String privStr = "MEECAQAwEwYHKoZIzj0CAQYIKoZIzj0DAQcEJzAlAgEBBCAQ7bMVIcWr9NpSD3hPkns5C0qET87UvyY5WI6UML2p0Q==";
String pubStr = "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAES8VdACZT/9u1NmaiQk0KIjEXxiaxms74nu/ps6bP0OvYMIlTdIWWU2s35LEKsNJH9u5QM2ocX53BPjwbsENXJw==";
PrivateKey privateKey = base64ToPrivateKey(privStr);
PublicKey publicKey = base64ToPublicKey(pubStr);
String str = "This is string to sign";
byte[] signature = signMsg(str, privateKey);
boolean ok = verifySignature(publicKey, str, signature);
System.out.println("signature ok:" + ok);
String privHex = getPrivateKeyAsHex(privateKey);
}
public static byte[] signMsg(String msg, PrivateKey priv) throws Exception {
Signature ecdsa = Signature.getInstance("SHA1withECDSA");
ecdsa.initSign(priv);
byte[] strByte = msg.getBytes("UTF-8");
ecdsa.update(strByte);
byte[] realSig = ecdsa.sign();
//the printed signature from here is what is used in the Go version (hex string)
System.out.println("Signature: " + new BigInteger(1, realSig).toString(16));
return realSig;
}
//https://stackoverflow.com/questions/30175149/error-when-verifying-ecdsa-signature-in-java-with-bouncycastle
private static boolean verifySignature(PublicKey pubKey, String msg, byte[] signature) throws Exception {
byte[] message = msg.getBytes("UTF-8");
Signature ecdsa = Signature.getInstance("SHA1withECDSA");
ecdsa.initVerify(pubKey);
ecdsa.update(message);
return ecdsa.verify(signature);
}
public static String generateKey() throws Exception {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC");
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
keyGen.initialize(256, random); //256 bit key size
KeyPair pair = keyGen.generateKeyPair();
PrivateKey priv = pair.getPrivate();
ECPrivateKey ePriv = (ECPrivateKey) priv;
PublicKey pub = pair.getPublic();
//https://stackoverflow.com/questions/5355466/converting-secret-key-into-a-string-and-vice-versa
String encodedPrivateKey = Base64.getEncoder().encodeToString(priv.getEncoded());
byte[] pubEncoded = pub.getEncoded();
String encodedPublicKey = Base64.getEncoder().encodeToString(pubEncoded);
System.out.println(encodedPrivateKey);
System.out.println(encodedPublicKey);
return encodedPrivateKey;
}
public static PrivateKey base64ToPrivateKey(String encodedKey) throws Exception {
byte[] decodedKey = Base64.getDecoder().decode(encodedKey);
return bytesToPrivateKey(decodedKey);
}
public static PrivateKey bytesToPrivateKey(byte[] pkcs8key) throws GeneralSecurityException {
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(pkcs8key);
KeyFactory factory = KeyFactory.getInstance("EC");
PrivateKey privateKey = factory.generatePrivate(spec);
return privateKey;
}
public static PublicKey base64ToPublicKey(String encodedKey) throws Exception {
byte[] decodedKey = Base64.getDecoder().decode(encodedKey);
return bytesToPublicKey(decodedKey);
}
public static PublicKey bytesToPublicKey(byte[] x509key) throws GeneralSecurityException {
X509EncodedKeySpec spec = new X509EncodedKeySpec(x509key);
KeyFactory factory = KeyFactory.getInstance("EC");
PublicKey publicKey = factory.generatePublic(spec);
return publicKey;
}
//https://stackoverflow.com/questions/40552688/generating-a-ecdsa-private-key-in-bouncy-castle-returns-a-public-key
private static String getPrivateKeyAsHex(PrivateKey privateKey) {
ECPrivateKey ecPrivateKey = (ECPrivateKey) privateKey;
byte[] privateKeyBytes = ecPrivateKey.getS().toByteArray();
System.out.println("S:"+ecPrivateKey.getS());
String hex = bytesToHex(privateKeyBytes);
System.out.println("Private key bytes: " + Arrays.toString(privateKeyBytes));
System.out.println("Private key hex: " + hex);
return hex;
}
private final static char[] hexArray = "0123456789ABCDEF".toCharArray();
public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0 ; j < bytes.length ; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
Doing the signing and verification in Java works just fine. Easy to configure of course, since they are all the same libs, parameters, and all.
To verify the same signature in Go, I tried:
func TestSigning(t *testing.T) {
privKey := hexToPrivateKey("10EDB31521C5ABF4DA520F784F927B390B4A844FCED4BF2639588E9430BDA9D1")
pubKey := privKey.Public()
sig := "3045022071f06054f450f808aa53294d34f76afd288a23749628cc58add828e8b8f2b742022100f82dcb51cc63b29f4f8b0b838c6546be228ba11a7c23dc102c6d9dcba11a8ff2"
sigHex, _ := hex.DecodeString(sig)
ePubKey := pubKey.(*ecdsa.PublicKey)
ok := verifyMySig(ePubKey, "This is string to sign", sigHex)
println(ok)
}
func verifyMySig(pub *ecdsa.PublicKey, msg string, sig []byte) bool {
r := new(big.Int).SetBytes(sig[:len(sig)/2])
s := new(big.Int).SetBytes(sig[len(sig)/2:])
return ecdsa.Verify(pub, []byte(msg), r, s)
}
func hexToPrivateKey(hexStr string) *ecdsa.PrivateKey {
bytes, _ := hex.DecodeString(hexStr)
k := new(big.Int)
k.SetBytes(bytes)
println("k:")
fmt.Println(k.String())
priv := new(ecdsa.PrivateKey)
curve := elliptic.P256()
priv.PublicKey.Curve = curve
priv.D = k
priv.PublicKey.X, priv.PublicKey.Y = curve.ScalarBaseMult(k.Bytes())
return priv
}
Initially, I tried to just export the Private key in Java as a base64 encoded string, and import that into Go. But I could not figure out how to get Go to load the key in the format Java stores if (X509EncodedKeySpec). So instead, I tried this way to copy the big integer of the private key only, and generate the public key from that. If I get that to work, then try to copy just the public key..
Anyway, the Go code fails to verify the signature. It is always false. Also, I cannot figure out where to put the SHA function in Go from "SHA1withECDSA" part.
I am sure I am missing some basic concepts here. How to do this properly?
Managed to get this to work. So just to document it for myself and anyone interested..
As pointed by in comments, the signature from Java is in ASN1 format. Found a nice description of the format here: https://crypto.stackexchange.com/questions/1795/how-can-i-convert-a-der-ecdsa-signature-to-asn-1.
I also found some good examples on how to do SHAxx with ECDSA in Go at https://github.com/gtank/cryptopasta (sign.go and sign_test.go). Just need to run the relevant SHA function before the ECDSA code.
Found example code for building the public keys from parameters in Go at http://codrspace.com/supcik/golang-jwt-ecdsa/.
I paste the relevant code below, if someone finds an issue, please let me know..
Relevant Java code:
public static PublicKey bytesToPublicKey(byte[] x509key) throws GeneralSecurityException {
X509EncodedKeySpec spec = new X509EncodedKeySpec(x509key);
KeyFactory factory = KeyFactory.getInstance("EC");
ECPublicKey publicKey = (ECPublicKey) factory.generatePublic(spec);
//We should be able to use these X and Y in Go to build the public key
BigInteger x = publicKey.getW().getAffineX();
BigInteger y = publicKey.getW().getAffineY();
System.out.println(publicKey.toString());
return publicKey;
}
//we can either use the Java standard signature ANS1 format output, or just take the R and S parameters from it, and pass those to Go
//https://stackoverflow.com/questions/48783809/ecdsa-sign-with-bouncycastle-and-verify-with-crypto
public static BigInteger extractR(byte[] signature) throws Exception {
int startR = (signature[1] & 0x80) != 0 ? 3 : 2;
int lengthR = signature[startR + 1];
return new BigInteger(Arrays.copyOfRange(signature, startR + 2, startR + 2 + lengthR));
}
public static BigInteger extractS(byte[] signature) throws Exception {
int startR = (signature[1] & 0x80) != 0 ? 3 : 2;
int lengthR = signature[startR + 1];
int startS = startR + 2 + lengthR;
int lengthS = signature[startS + 1];
return new BigInteger(Arrays.copyOfRange(signature, startS + 2, startS + 2 + lengthS));
}
public static byte[] signMsg(String msg, PrivateKey priv) throws Exception {
Signature ecdsa = Signature.getInstance("SHA1withECDSA");
ecdsa.initSign(priv);
byte[] strByte = msg.getBytes("UTF-8");
ecdsa.update(strByte);
byte[] realSig = ecdsa.sign();
//this is the R and S we could also pass as the signature
System.out.println("R: "+extractR(realSig));
System.out.println("S: "+extractS(realSig));
return realSig;
}
Relevant Go code:
func verifyMySig(pub *ecdsa.PublicKey, msg string, sig []byte) bool {
//https://github.com/gtank/cryptopasta
digest := sha1.Sum([]byte(msg))
var esig ecdsaSignature
asn1.Unmarshal(sig, &esig)
//above is ASN1 decoding from the Java format. Alternatively, we can just transfer R and S parameters and set those
// esig.R.SetString("89498588918986623250776516710529930937349633484023489594523498325650057801271", 0)
// esig.S.SetString("67852785826834317523806560409094108489491289922250506276160316152060290646810", 0)
fmt.Printf("R: %d , S: %d", esig.R, esig.S)
println()
return ecdsa.Verify(pub, digest[:], esig.R, esig.S)
}
func hexToPrivateKey(hexStr string) *ecdsa.PrivateKey {
bytes, err := hex.DecodeString(hexStr)
print(err)
k := new(big.Int)
k.SetBytes(bytes)
println("k:")
fmt.Println(k.String())
priv := new(ecdsa.PrivateKey)
curve := elliptic.P256()
priv.PublicKey.Curve = curve
priv.D = k
priv.PublicKey.X, priv.PublicKey.Y = curve.ScalarBaseMult(k.Bytes())
//we can check these against the Java implementation to see if it matches to know key was transferred OK
fmt.Printf("X: %d, Y: %d", priv.PublicKey.X, priv.PublicKey.Y)
println()
return priv
}
I'm trying to save a key in an XML file for later decryption of a encrypted string, the software can encrypt and return me at the "Encrypt()" method, but returns error when trying to use the "Decrypt()" method
Code
private static Cipher ecipher;
private static Cipher dcipher;
public static String[] encrypt(String str) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException {
String Key, res;
SecretKey key;
String[] Return = new String[2];
key = KeyGenerator.getInstance("DES").generateKey();
ecipher = Cipher.getInstance("DES");
ecipher.init(Cipher.ENCRYPT_MODE, key);
byte[] utf8 = str.getBytes("UTF8");
byte[] enc = ecipher.doFinal(utf8);
enc = BASE64EncoderStream.encode(enc);
res = new String(enc);
//Returning values 0 = Encrypted String 1 = Key For Storage in XML
Return[0] = res;
byte[] keyBytes = key.getEncoded();
Key = new String(keyBytes,"UTF8");
Return[1] = Key;
return Return;
}
public static String decrypt(String str, String Key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, UnsupportedEncodingException, BadPaddingException {
SecretKey key = new SecretKeySpec(Key.getBytes("UTF8"), "DES");
dcipher = Cipher.getInstance("DES");
dcipher.init(Cipher.DECRYPT_MODE, key);
byte[] dec = BASE64DecoderStream.decode(str.getBytes());
byte[] utf8 = dcipher.doFinal(dec);
return new String(utf8, "UTF8");
}
Console Return :
run:
Encryped String : EB6uhzsBl08=
Key : �g�uX8p
Sep 07, 2014 6:35:17 PM Software.Software main
SEVERE: null
java.security.InvalidKeyException: Invalid key length: 12 bytes
at com.sun.crypto.provider.DESCipher.engineGetKeySize(DESCipher.java:373)
at javax.crypto.Cipher.passCryptoPermCheck(Cipher.java:1062)
at javax.crypto.Cipher.checkCryptoPerm(Cipher.java:1020)
at javax.crypto.Cipher.implInit(Cipher.java:796)
at javax.crypto.Cipher.chooseProvider(Cipher.java:859)
at javax.crypto.Cipher.init(Cipher.java:1229)
at javax.crypto.Cipher.init(Cipher.java:1166)
at Software.Encryption.decrypt(Encryption.java:51)
at Software.Software.main(main.java:30)
BUILD SUCCESSFUL (total time: 1 second)
You have to encode the key in base64
public static String[] encrypt(String str) throws NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException,
UnsupportedEncodingException, IllegalBlockSizeException,
BadPaddingException {
String Key, res;
SecretKey key;
String[] Return = new String[2];
key = KeyGenerator.getInstance("DES").generateKey();
ecipher = Cipher.getInstance("DES");
ecipher.init(Cipher.ENCRYPT_MODE, key);
byte[] utf8 = str.getBytes("UTF8");
byte[] enc = ecipher.doFinal(utf8);
enc = BASE64EncoderStream.encode(enc);
res = new String(enc);
// Returning values 0 = Encrypted String 1 = Key For Storage in XML
Return[0] = res;
byte[] keyBytes = key.getEncoded();
Key = new String(BASE64EncoderStream.encode(keyBytes), "UTF8");
Return[1] = Key;
return Return;
}
public static String decrypt(String str, String Key)
throws NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeyException, IllegalBlockSizeException,
UnsupportedEncodingException, BadPaddingException {
SecretKey key = new SecretKeySpec(BASE64DecoderStream.decode(Key.getBytes("UTF8")), "DES");
dcipher = Cipher.getInstance("DES");
dcipher.init(Cipher.DECRYPT_MODE, key);
byte[] dec = BASE64DecoderStream.decode(str.getBytes());
byte[] utf8 = dcipher.doFinal(dec);
return new String(utf8, "UTF8");
}
Before you mark this as a duplicate, please read the full question.
I've looked through countless questions here about this problem, and every answer said to install JCE. However, if I want to send the program to someone else, another computer, virtually anything off the development computer, they have to install JCE too.
Is there a way I can use a smaller keysize without having to install anything?
My encryption method;
public static String encrypt(String in) throws NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException,
IllegalBlockSizeException, BadPaddingException, IOException {
String out = " ";
// generate a key
KeyGenerator keygen = KeyGenerator.getInstance("AES");
keygen.init(128);
byte[] key = keygen.generateKey().getEncoded();
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
// build the initialization vector
SecureRandom random = new SecureRandom();
byte iv[] = new byte[16]; //generate random 16 byte IV. AES is always 16bytes
random.nextBytes(iv);
IvParameterSpec ivspec = new IvParameterSpec(iv);
saveKey(key, iv); //<-- save to file
// initialize the cipher for encrypt mode
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivspec);
byte[] encrypted = cipher.doFinal(in.getBytes());
out = asHex(encrypted);
return out;
}
And my decrypt method:
public static String decrypt(String in) throws NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException,
IllegalBlockSizeException, BadPaddingException, IOException, KeyFileNotFoundException, UnknownKeyException {
String out = " ";
byte[] key = readKey("key").clone(); //<--from file
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
byte[] iv = readKey("iv"); //<-- from file
IvParameterSpec ivspec = new IvParameterSpec(iv);
//initialize the cipher for decryption
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivspec);
// decrypt the message
byte[] decrypted = cipher.doFinal(in.getBytes());
out = asHex(decrypted);
return out;
}
My saveKey() method:
private static void saveKey(byte[] key, byte[] iv) throws FileNotFoundException, IOException {
File keyFile = new File(Logging.getCurrentDir() + "\\cikey.key");
keys.setProperty("key", asHex(key));
keys.setProperty("iv", asHex(iv));
keys.store(new FileOutputStream(keyFile.getAbsolutePath(), false), null);
}
My readKey() method:
private static byte[] readKey(String request) throws KeyFileNotFoundException, UnknownKeyException, FileNotFoundException, IOException {
File keyFile = new File(Logging.getCurrentDir() + "\\cikey.key");
byte[] storage;
keys.load(new FileInputStream(keyFile));
if (!keyFile.exists())
throw new KeyFileNotFoundException("Key file not located.");
if (keys.containsKey(request) == false)
throw new UnknownKeyException("Key not found.");
else
storage = keys.getProperty(request).getBytes();
return storage;
}
asHex() method (transferring array to String):
public static String asHex(byte buf[]) {
StringBuilder strbuf = new StringBuilder(buf.length * 2);
for (int i = 0; i < buf.length; i++) {
if (((int) buf[i] & 0xff) < 0x10)
strbuf.append("0");
strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
}
return strbuf.toString();
}
Is there a way I can use a smaller keysize without having to install anything?
You can't use AES with keys sizes smaller than 128 bit, but there are other ciphers available: DES, Blowfish, etc. They aren't as secure as AES, but still can do the trick if your application (as most apps do) does not worth complicated hacking effort. Here's an example for 56 bit DES:
public static String encrypt(String in) throws Exception {
String out = " ";
// generate a key
KeyGenerator keygen = KeyGenerator.getInstance("DES");
keygen.init(56);
byte[] key = keygen.generateKey().getEncoded();
SecretKeySpec skeySpec = new SecretKeySpec(key, "DES");
// build the initialization vector
SecureRandom random = new SecureRandom();
byte iv[] = new byte[8]; //generate random 8 byte IV.
random.nextBytes(iv);
IvParameterSpec ivspec = new IvParameterSpec(iv);
// initialize the cipher for encrypt mode
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivspec);
byte[] encrypted = cipher.doFinal(in.getBytes());
out = asHex(encrypted);
return out;
}
There is also a problem with storing and reading the keys in the code. You're storing them as hex, but reading as symbols from default platform encoding. Here's an example how to make both operations uniform:
private static void saveKey(byte[] key, byte[] iv) throws IOException {
File keyFile = new File("C:/cikey.key");
keys.setProperty("key", toHexString(key));
keys.setProperty("iv", toHexString(iv));
keys.store(new FileOutputStream(keyFile.getAbsolutePath(), false), null);
}
private static byte[] readKey(String request) throws IOException {
File keyFile = new File("C:/cikey.key");
keys.load(new FileInputStream(keyFile));
return toByteArray(keys.getProperty(request));
}
public static String toHexString(byte[] array) {
return DatatypeConverter.printHexBinary(array);
}
public static byte[] toByteArray(String s) {
return DatatypeConverter.parseHexBinary(s);
}