a7firm/src/sega/a7/HmacSha1.java

60 lines
2.4 KiB
Java

package sega.a7;
import javacard.framework.JCSystem;
import javacard.framework.Util;
import javacard.security.MessageDigest;
public class HmacSha1 {
public static short HMAC_BLOCK_SIZE = 64;
public static short INNER_PAD = 54;
public static short OUTER_PAD = 92;
private byte[] m_ramD_key = JCSystem.makeTransientByteArray(HMAC_BLOCK_SIZE, (byte) 1);
private byte[] m_ramD_padBuffer = JCSystem.makeTransientByteArray(HMAC_BLOCK_SIZE, (byte) 1);
private MessageDigest m_ee_sha1 = MessageDigest.getInstance((byte) 1, false);
public boolean update(byte[] inBuff, short inOffset, short inLength) {
if (inBuff == null || inLength <= 0 || inBuff.length < inOffset)
return false;
this.m_ee_sha1.update(inBuff, inOffset, inLength);
return true;
}
public boolean sign(byte[] inBuff, short inOffset, short inLength, byte[] sigBuff, short sigOffset) {
if (inBuff == null || inLength <= 0 || sigBuff == null || inOffset + inLength > inBuff.length
|| sigOffset + 20 > sigBuff.length)
return false;
this.m_ee_sha1.doFinal(inBuff, inOffset, inLength, sigBuff, sigOffset);
for (short ii = 0; ii < HMAC_BLOCK_SIZE; ii++)
this.m_ramD_padBuffer[ii] = (byte) (this.m_ramD_key[(short) ii] ^ OUTER_PAD);
this.m_ee_sha1.update(this.m_ramD_padBuffer, (short) 0, (short) this.m_ramD_padBuffer.length);
this.m_ee_sha1.doFinal(sigBuff, sigOffset, (short) 20, sigBuff, sigOffset);
return true;
}
public boolean init(byte[] key, short offset, short length) {
if (key == null || length <= 0 || key.length < offset + length)
return false;
if (length > this.m_ramD_key.length) {
this.m_ee_sha1.reset();
this.m_ee_sha1.doFinal(key, offset, length, this.m_ramD_key, (short) 0);
} else {
Util.arrayCopyNonAtomic(key, offset, this.m_ramD_key, (short) 0, length);
}
if (length < this.m_ramD_key.length) {
Util.arrayFillNonAtomic(this.m_ramD_key, length, (short) (this.m_ramD_key.length - length), (byte) 0);
}
this.m_ee_sha1.reset();
for (short ii = 0; ii < HMAC_BLOCK_SIZE; ii++) {
this.m_ramD_padBuffer[ii] = (byte) (this.m_ramD_key[ii] ^ INNER_PAD);
}
this.m_ee_sha1.init(this.m_ramD_padBuffer, (short) 0, (short) this.m_ramD_padBuffer.length);
return true;
}
}